PHP 中的后期静态绑定是什么?

phpserver side programmingprogramming更新于 2025/10/6 6:52:17

后期静态绑定的基本思想是,继承的概念和"self"关键字的概念并不遵循相同的规则。例如,在子类中调用父类中的方法"fun",并不会使"self"引用子类(正如预期的那样)。

后期静态绑定的概念引入了一个新的关键字"static",使用该关键字时,会将函数绑定到运行时类(即函数首次被调用的类)。此外,任何静态函数或变量通常在运行时执行,而不是在编译时执行。因此,如果需要将值动态赋给静态变量,则会在运行时进行,这称为后期静态绑定。

示例

<?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 "
"; Professor::getAge(); ?>

输出

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

一个名为"student"的类包含一个姓名和一个用于获取姓名的函数。另一个函数用于获取学生的年龄。一个名为"professor"的类扩展了学生类,并且该函数也被继承。获取年龄的函数在学生和教授的实例上都会被调用。


相关文章