Junior — Middle
Can you explain what late static binding in PHP is and how it differs from other types of binding?
sobes.tech AI
Answer from AI
Late Static Binding (LSB) in PHP is a mechanism that allows static methods and properties of a class to refer to the calling class, rather than the class where the method was defined.
The difference from regular static binding is that with a normal call via self::, the class in which the method is declared is always used, whereas with late static binding via static::, the class that actually called the method (runtime class) is used.
Example:
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who(); // always A
static::who(); // late static binding
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
// Outputs:
// A (from self::who())
// B (from static::who())
Thus, LSB allows creating more flexible and extendable classes, where behavior depends on the subclass, not just the parent class.