PHP Late Static Bindings

PHPServer Side ProgrammingProgramming

Introduction

This feature of late static binding in PHP is used to refercalled class in static inheritance. When static methods are called, name of class is attached with scope resolution operator (::) while in case of other instance methods we call them using name of object. The static:: will not be resolved using the class in which method is defined ,instead will be computed using runtime information. Static references to the current class are resolved using the class in which the function belongs, not where it was defined

Example

In following code, parent class calls static ethod with self:: prefix. Same method when called with child class doesn't refer to child class name as it is not resolved

Example

 Live Demo

<?php
class test1{
   public static $name="Raja";
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
   public static function getname(){
      self::name();
   }
}
class test2 extends test1{
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
}
test2::getname();
?>

Output

Result shows that agains expectation, name of parent class is returned

name of class :test1

Using static:: instead of self:: creates late binding at runtime

Example

 Live Demo

<?php
class test1{
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
   public static function getname(){
      static::name();
   }
}
class test2 extends test1{
   public static function name(){
      echo "name of class :" . __CLASS__;
   }
}
test2::getname();
?>

Above code now returns name of child class as expected

Output

name of class :test2

Using static:: in non-static context

Private method in parent is copied to child, hence its scope will still be parent

Example

 Live Demo

<?php
class test1{
   private function name(){
      echo "name of class :" . __CLASS__ ."\n";
   }
   public function getname(){
      $this->name();
      static::name();
   }
}
class test2 extends test1{
   //
}
$t2=new test2();
$t2->getname();
?>

Output

Output shows following result

name of class :test1
name of class :test1

However, when parent method is overridden, its scope changes

Example

class test3 extends test1{
   private function name() {
      /* original method is replaced; the scope of name is test3 */
   }
}
$t3 = new test3();
$t3->name();

Output

Output shows following exception

PHP Fatal error: Uncaught Error: Call to private method test3::name() from context ''
raja
Published on 18-Sep-2020 11:48:26

Advertisements