What is Late Static Bindings in PHP ?
Last Updated :
02 Mar, 2020
In PHP, programs are saved and then directly run on the browser, the script is executed through a web server and we get the output. We don’t compile PHP programs manually but that does not mean it is never compiled. The PHP interpreter does that for you and runs it. So there are two phases, first, compile-time and second run time. During the compile time, the normal variables are replaced with their values but the static keywords are replaced only in the run time. Overriding a property in child class and creating the instance of the child class, so to get the overridden output, the late static binding concept is used by writing static keyword before using the property. Whenever a PHP interpreter gets the request to compile a function. If it sees any static property, then it leaves the property pending for run time and the property gets its value during runtime from the function it is being called. This is called late static binding.
This feature of late static binding was introduced in PHP 5.3 and above, previous versions will show a fatal error.
Below examples illustrate late static binding in PHP:
Example 1: In below code, we have a class Car and its child class newCar. We are getting some problem whenever we try to access the getOwner() function via scope resolution operator (without creating an object). Both classes have getCar() function but whenever we call getOwner() function through newCar class, it will inherit the getCar() function in class Car instead of newCar.
Example 2: Late static binding on const, it will work the same as static methods which means how it is being called. For const, it need not be necessarily static.
- Program:
<?php
class One
{
const MY_CONST = false;
public function selfConst()
{
return self::MY_CONST;
}
public function staticConst()
{
return static ::MY_CONST;
}
}
class Two extends One
{
const MY_CONST = true;
}
$two = new Two();
echo $two ->selfConst() ? 'yes' : 'no' ;
echo "\n" ;
echo $two ->staticConst() ? 'yes' : 'no' ;
?>
|
- Output:
no
yes
Where to use it ?
- Where a function is overridden and you want to display the new properties.
- Where the program is too big, and you cannot write the same function again and again.
Share your thoughts in the comments
Please Login to comment...