PHP后期静态绑定

2023年11月22日13:58:21

介绍

PHP中后期静态绑定的此功能用于在静态继承中引用类。当调用静态方法时,类名将与范围解析运算符(::)附加在一起,而在其他实例方法的情况下,我们使用对象名来调用它们。static ::不会使用定义方法的类来解析,而是使用运行时信息来计算。对当前类的静态引用是使用函数所属的类(而不是定义其的类)来解析的

示例

在以下代码中,父类使用self ::前缀调用静态方法。与子类调用时相同的方法未引用子类名称,因为它无法解析

示例

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

输出结果

结果显示再次期望,返回父类的名称

类名称:test1

使用static ::而不是self ::在运行时创建后期绑定

示例

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

上面的代码现在按预期返回子类的名称

输出结果

类名称:test2

在非静态上下文中使用static ::

父级中的私有方法被复制到子级,因此其作用域仍将是父级

示例

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

输出结果

输出显示以下结果

类名称:test1
类名称:test1

但是,当父方法被覆盖时,其范围会改变

示例

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

输出结果

输出显示以下异常

PHP Fatal error: Uncaught Error: Call to private method test3::name() from context ''

  • 更新时间:2023年11月22日13:58:21 ,共 1416 字。