What are late static bindings in PHP?

PHPServer Side ProgrammingProgramming

The basic idea behind late static bindings is that the concept of inheritance and the concept of ‘self’ keyword don’t follow the same rules. For example, a method ‘fun’ in parent class called in the child class won’t make ‘self’ refer to the child (as expected).

The concept of late static bindings brings in a new keyword ‘static’, which when used, binds the function to the runtime class, or the class where the function was first used. In addition to this, any static function or variable is usually executed during runtime and not during compile time. Hence, if a value needs to be dynamically assigned to a variable that is static, it happens during runtime, and this is known as late static binding.

Example

 Live Demo

<?php
class student
{
   public static $my_name = 'Joe';
   public static function getName()
   {
      return "The name of the student is : " . self::$my_name;
   }
   public static function getAge()
   {
      echo static::getName();
   }
}
class Professor extends student
{
   public static function getName()
   {
      return "The name of the student is : " . self::$my_name . " and age is 24.";
   }
}
student::getAge();
echo "\n";
Professor::getAge();
?>

Output

The name of the student is : Joe
The name of the student is : Joe and age is 24.

A class named ‘student’ contains a name and a function that fetches the name. Another function fetches the age of the student. A class named ‘professor’ extends the student class and the function is also inherited. The function to fetch the age is called on instance of both student and professor.

raja
Published on 01-Jul-2020 10:41:14
Advertisements