PHP

What is Late Static Bindings in PHP with Examples2 min read

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.

The output of above script is A. It is what we expected. Let’s move to another example.

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.

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.

Leave a Comment