Late Static Binding is a very important concept in PHP. In this tutorial, We’ll learn what is late static binding and how to use this concept.
In PHP, late static binding is used to reference the called class in the context of static inheritance.
Before deep diving into the concept of late static binding, let’s understand the difference between self and static in PHP.
Self Vs Static in PHP
When we use self keyword in a class, It will always relate to the class where it is mentioned not the class which is inheriting it. Let’s understand this concept through example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php class A { public static function printClass() { return self::getClassName(); } public static function getClassName() { return __class__; } } echo A::printClass(); // A is printed |
The output of above script is A. It is what we expected. Let’s move to another example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php class A { public static function printClass() { return self::getClassName(); } public static function getClassName() { return __class__; } } class B extends A { public static function getClassName() { return __class__; } } echo B::printClass(); // Still it prints A |
Still, the output of this script is A. The printClass method is defined inside Class A. Class B extends Class A. When we call printClass method, the scope of this method is still inside the Class A.
NOTE – self keyword in PHP refers to the class it is located in, and not necessarily a class that extends it.
Late Static Binding in PHP
To solve this problem, the concept of late static binding comes. Let’s use the static keyword instead of self.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php class A { public static function printClass() { return static::getClassName(); } public static function getClassName() { return __class__; } } class B extends A { public static function getClassName() { return __class__; } } echo B::printClass(); // Prints B echo A::printClass(); // Prints A |
When we use static keyword, It will reference the class that is called at runtime.
As per php.net Manual
This feature was named “late static bindings” with an internal perspective in mind. “Late binding” comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a “static binding” as it can be used for (but is not limited to) static method calls.