PHP 延迟静态绑定
简介
PHP 中的延迟静态绑定功能用于在静态继承中引用被调用的类。当调用静态方法时,类名与作用域解析运算符 (::) 一起使用,而在其他实例方法的情况下,我们使用对象名来调用它们。static:: 不会使用定义方法的类来解析,而是使用运行时信息计算。对当前类的静态引用使用函数所属的类来解析,而不是它被定义的位置。
示例
在以下代码中,父类使用 self:: 前缀调用静态方法。当使用子类调用相同的方法时,它不会引用子类名,因为它没有被解析。
示例
<?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();
?>输出
结果显示,与预期相反,返回了父类名。
name of class :test1
使用 static:: 代替 self:: 会在运行时创建延迟绑定。
示例
<?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();
?>上面的代码现在按预期返回子类名。
输出
name of class :test2
在非静态上下文中使用 static::
父类中的私有方法被复制到子类,因此它的作用域仍然是父类。
示例
<?php
class test1{
private function name(){
echo "name of class :" . __CLASS__ ."
";
}
public function getname(){
$this->name();
static::name();
}
}
class test2 extends test1{
//
}
$t2=new test2();
$t2->getname();
?>输出
输出显示以下结果
name of class :test1 name of class :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 ''
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP