What is late static binding in PHP?
sobes.tech AI
Answer from AI
This is a mechanism that allows referencing the called class in the context of static calls. It solves the problem associated with self-references in inheriting classes when using the static:: keyword.
Let's consider an example using self:::
<?php
class A {
public static function who() {
echo __CLASS__; // Will output A
}
public static function test() {
self::who(); // Calls A::who()
}
}
class B extends A {
public static function who() {
echo __CLASS__; // Will output B
}
}
B::test(); // Will output A
In this case, self::who() inside class A will always call the who method from class A, even if the call to test() is made from class B.
Now let's look at an example using static:::
<?php
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // Calls the who() from the class that initiated the call to test()
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test(); // Will output B
Here, static::who() inside class A when called from class B will refer to class B and call the who() method from class B.
Late static binding allows dynamically determining which class to use in the context of a static call depending on which class was actually called. This becomes especially useful when working with class hierarchies and static methods that should behave polymorphically. It works by remembering the "called non-rebound class" (the final class in the inheritance chain from which the static call started) and using it to resolve static:: references.