PHP中的延迟静态绑定是什么?
延迟静态绑定的基本思想是,继承概念和“self”关键字的概念不遵循相同的规则。例如,在子类中调用的父类中的方法“fun”不会使“self”指向子类(如预期的那样)。
延迟静态绑定的概念引入了新的关键字“static”,使用该关键字时,它会将函数绑定到运行时类,或首次使用函数的类。除此之外,任何 static 函数或变量通常在运行时执行,而不是在编译时执行。因此,如果需要将值动态分配给 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”的类扩展了“student”类,并且还继承了该函数。对 student 和 professor 的实例调用获取年龄的函数。
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP