Late Static Binding in PHP

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.

Singleton design pattern

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.

 htaccess Tutorial

 

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.

PHP Composer

PHP Built-in Web Server

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.