Late static binding
Late Static Binding (LSB) is a feature introduced in PHP 5.3.0 that provides a way to reference the called class in a context of static inheritance.
Problem
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
self::who();
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
You might expect the output of B::test();
to be "B" because class B
has overridden the who
method. But it's not. The output is "A". This is because of the way the self
keyword works: it references the class in which the method is defined, not the class that was called.
Solution
Late Static Binding provides a way to solve this by introducing the static
keyword which, when used in this context, references the class that was originally called, not necessarily the class where the method is defined.
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Here's the LSB magic!
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test();
Now, the output of B::test();
is indeed "B". By using static::
instead of self::
, we're referencing the called class, not the defining class.
class A {
protected static $value = 'Class A';
public static function getValue() {
return static::$value; // Using the `static` keyword for late static binding
}
}
class B extends A {
protected static $value = 'Class B';
}
echo A::getValue(); // Outputs: Class A
echo B::getValue(); // Outputs: Class B
Why is important
Late Static Bindings are especially useful in the context of building base classes and frameworks where you have methods in a parent class that need to operate with static members or methods of a child class.
Without LSB, developers would often have to override parent methods entirely just to change one small part, which could lead to a lot of code duplication. With LSB, the base methods can be defined in the parent class and they will correctly use static members or methods of the child class when called from a child context.
class A {
protected static $value = 'Class A';
public static function getValue() {
return static::$value; // Using the `static` keyword for late static binding
}
}
class B extends A {
protected static $value = 'Class B';
}
echo A::getValue(); // Outputs: Class A
echo B::getValue(); // Outputs: Class B
Last updated