新自我与新静态 [英] New self vs. new static
问题描述
我正在转换一个PHP 5.3库以在PHP 5.2上工作.阻碍我前进的主要因素是使用后期静态绑定(如return new static($options);
),如果将其转换为return new self($options)
,是否可以获得相同的结果?
I am converting a PHP 5.3 library to work on PHP 5.2. The main thing standing in my way is the use of late static binding like return new static($options);
, if I convert this to return new self($options)
will I get the same results?
new self
和new static
有什么区别?
推荐答案
我会得到相同的结果吗?
will I get the same results?
并非如此.不过,我不知道针对PHP 5.2的解决方法.
Not really. I don't know of a workaround for PHP 5.2, though.
new self
和new static
有什么区别?
self
指的是实际编写new
关键字的同一类.
self
refers to the same class in which the new
keyword is actually written.
static
指的是您在层次结构中调用该方法的任何类.
static
, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.
在下面的示例中,B
继承了A
的两个方法. self
调用绑定到A
,因为它是在A
的第一个方法的实现中定义的,而static
绑定到被调用的类(另请参见
In the following example, B
inherits both methods from A
. The self
invocation is bound to A
because it's defined in A
's implementation of the first method, whereas static
is bound to the called class (also see get_called_class()
).
class A {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class B extends A {}
echo get_class(B::get_self()); // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A
这篇关于新自我与新静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!