Sobes.tech
Junior — Middle

Can you explain the concept of late static binding in the context of programming?

sobes.tech AI

Answer from AI

Late static binding is a mechanism in programming that allows static methods to refer to the calling class rather than the class in which they are defined.

In PHP, this is important when inheritance is involved, and a static method is called from a child class. Late static binding allows using the keyword static:: instead of self::, so that the method can correctly work with the subclass.

Example:

class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();     // always calls A::who()
        static::who();   // calls the method of the class from which test() is called
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test(); // self::who() will output 'A', static::who() will output 'B'

Thus, late static binding allows creating more flexible and extendable classes.