I've recently been working on some class files and I've noticed that the member variables had been set in a protected static mode like protected static $_someVar and accessed like static::$_someVar.
I understand the concept of visibility and that having something set as protected static will ensure the member variable can only be accessed in the super class or derived classes but can I access protected static variables only in static methods?
Thanks
If I understand correctly, what you are referring to is called late-static bindings. If you have this:
If you change the
self
bit to:Then do:
Because
self
refers to the class where$_foo
was defined (A), whilestatic
references the class that called it at runtime (B).And of course, yes you can access static protected members outside a static method (i.e.: object context), although visibility and scope still matters.
Static variables exist on the class, rather than on instances of the class. You can access them from non-static methods, invoking them something like:
The reason this works is that
self
is a reference to the current class, rather than to the current instance (like$this
).By way of demonstration:
Output is
barbar
. However, if you try to access it directly:Then PHP will properly complain at you for trying to access a protected member.