The problem you have is that you have not defined an __unset()
magic method.
This means that when you call unset($myExample->my_property)
, it is trying to directly unset a public property with the specified name.
In example 1, the real protected property has an underscore in it's name. Therefore, when you try to unset the property, PHP looks at the object, sees that there is nothing with the specified name, and effectively ignores it.
This is the same behaviour that unset()
would exhibit if you tried to unset a non-existent variable or array element.
However in example 2, the protected property has the same name as you have given in the unset()
call.
In this example, PHP looks at the object and sees that the property does exist but that it it is non-accessible. It therefore throws an error complaining that it can't unset the property.
You can resolve this issue by including an __unset()
method alongside your __get()
and __set()
methods. If you're planning to use magic methods, you should ideally define all three.
Hope that helps.