Late static binding
suggest changeSince PHP 5.3, late static binding chooses the class a static call uses. It fixes self::, which always means the class that wrote the method. Take the following code:
class Horse {
public static function whatToSay() {
echo 'Neigh!';
}
public static function speak() {
self::whatToSay();
}
}
class MrEd extends Horse {
public static function whatToSay() {
echo 'Hello Wilbur!';
}
}
You would expect that the MrEd class will override the parent whatToSay() function. But when we run this we get something unexpected
Horse::speak(); // Neigh!
MrEd::speak(); // Neigh!
self::whatToSay() always means Horse, the class that contains speak(). static:: means the class named in the call, so MrEd::speak() runs MrEd::whatToSay(). There is no instance in these calls. The next Horse replaces self:: with static::. MrEd stays the subclass above. The two class declarations cannot sit in the same file.
class Horse {
public static function whatToSay() {
echo 'Neigh!';
}
public static function speak() {
static::whatToSay(); // Late Static Binding
}
}
Horse::speak(); // Neigh!
MrEd::speak(); // Hello Wilbur!
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents