本文目录一览:
PHP Static延迟静态绑定用法分析
本文实例讲述了PHP Static延迟静态绑定用法。分享给大家供大家参考,具体如下:
PHP5.3以后引入了延迟静态绑定static
,它是为了解决什么问题呢?PHP的继承模型中有一个存在已久的问题,那就是在父类中引用扩展类的最终状态比较困难。来看一个例子。
class A {
public static function echoClass() {
echo __CLASS__;
}
public static function test() {
self::echoClass();
}
}
class B extends A {
public static function echoClass() {
echo __CLASS__;
}
}
B::test(); // 输出 A
在PHP5.3中加入了一个新特性:延迟静态绑定,就是把本来在定义阶段固定下来的表达式或变量,改在执行阶段才决定,比如当一个子类继承了父类的静态表达式的时候,它的值并不能被改变,有时不希望看到这种情况。 下面的例子解决了上面提出的问题:
class A {
public static function echoClass() {
echo __CLASS__;
}
public static function test() {
static::echoClass();
}
}
class B extends A {
public static function echoClass() {
echo __CLASS__;
}
}
B::test(); // 输出 B
第8行的static::echoClass();
定义了一个静态延迟绑定方法,直到B
调用test
的时候才执行原本定义的时候执行的方法。
希望本文所述对大家PHP程序设计有所帮助。
php Late static binding 是什么?
PHP延迟静态绑定 Late Static Binding
推荐阅读以下内容:
As of PHP 5.3.0, PHP implements a feature called late static bindings which can be used to reference the called class in a context of static inheritance.
More precisely, late static bindings work by storing the class named in the last "non-forwarding call". In case of static method calls, this is the class explicitly named (usually the one on the left of the ::
operator); in case of non static method calls, it is the class of the object. A "forwarding call" is a static one that is introduced by self::
, parent::
, static::
, or, if going up in the class hierarchy, forward_static_call()
. The function get_called_class()
can be used to retrieve a string with the name of the called class and static::
introduces its scope.
This feature was named "late static bindings" with an internal perspective in mind. "Late binding" comes from the fact that static::
will not be resolved using the class where the method is defined but it will rather be computed using runtime information. It was also called a "static binding" as it can be used for (but is not limited to) static method calls.
如何理解php中的后期静态绑定
使用的保留关键字:
static
定义:static::
不再被解析为定义当前方法所在的类,而是在实际运行时计算的。也可以称之为“静态绑定”,因为它可以用于(但不限于)静态方法的调用。
self
与 static
的区别
self
调用的就是本身代码片段这个类,而static
调用的是从堆内存中提取出来,访问的是当前实例化的那个类(即static
作用于当前调用的类)。
示例一(在静态环境下)
class A {
public static function who() {
echo __CLASS__;
}
public static function test() {
static::who(); // 后期静态绑定从这里开始
}
}
class B extends A {
public static function who() {
echo __CLASS__;
}
}
B::test(); // 输出结果是 "B"