I’m having difficulty understanding how ‘static’ stuff works in PHP. Can someone point me to a good tutorial on this? One that comprehensively covers the topic?
I understand the use of static variables within a function, and also static members in a class. Beyond that, however, it gets a bit hazy.
For example: I see that static methods can be called without instantiating a class. Not sure why this is important though, since you can call a non-static method in exactly the same way, provided it does not reference $this
Late static binding is another area of confusion, along with when and where I can use the scope resolution operator. (It seems I can use it to call parent methods irrespective of whether they are static or not…)
Am I the only one struggling with this?
While you can call a non-static method without an instance, this will trigger an
E_STRICTwarning. The whole point of static methods is for accessing static variables on the class, but many people use it as a way to logically group utility functions rather than define a bunch of global functions.When you call a static method using the class’s name, e.g.
Class::foo(), there is no instance and thus no polymorphism. Thefoodefined byClassis called directly. If it doesn’t define such a method, its superclasses are searched until one is found that does.When you call a static method using the
selfkeyword from a class method, e.g.self::foo(), it works just as if you were to replaceselfwith the name of the class holding the calling code.When you call a static method using the
statickeyword from a class method, e.g.static::foo(), you are invoking late static binding. Instead of starting the search forfooin the current class, it starts from the current class context, the class that was initially statically-referenced.Late static binding works similarly with static class properties, but the property must be defined in the child class itself. Assigning a new property to a class (e.g.
Child::$foo = 'foo') will not make it available for LSB from the parent.