called class in a context static inheritance. Before diving deep into this topic lets discuss the keywords like self and static in PHP . In PHP, you use the self keyword to access static properties and methods of classes.Self is resolved at compile time, which means that when class is inherited from another class, self will always relate to the class where it is mentioned not the class which is inheriting it. Here is example of use of self
As shown in above example, self is referring to the class A(Base Class) in both cases and function get_classname from class A has been called Twice. To overcome the limitation, late static binding comes to the picture. Late static binding tries to solve this limitation by introducing a keyword that references the class that was initially called at runtime. It was decided not to introduce a new keyword but rather use static that was already reserved. In the above example by just replacing the self keyword with the static output of the code will change as following.
Use of late static binding
In the following example, singleton class is created using the late static binding.With the help of late static binding here in the following program we have choice of using same get_instance function to create the objects of both classes(Singleton class and B class ). get_instance function checks to see if an instance of the class has been created yet or not. If it hasn’t it creates a new instance. If it has been created before, it returns the singleton instance which was previously created. The other important part is that you need to make the constructor function “private”. This ensures that the class can not be instantiated outside the class, only the get_instance function can be used to create it.
Trending Tutorials