我正在转换 PHP 5.3 库以在 PHP 5.2 上运行。阻碍我的主要事情是使用后期静态绑定(bind),如 return new static($options);
,如果我将其转换为 return new self($options)
我会得到相同的结果吗?
new self
和new static
有什么区别?
最佳答案
will I get the same results?
不是真的。不过,我不知道 PHP 5.2 的解决方法。
What is the difference between
new self
andnew static
?
self
指的是实际写入 new
关键字的类。
static
,在 PHP 5.3 的后期静态绑定(bind)中,指的是层次结构中您调用该方法的任何类。
在以下示例中,B
从 A
继承了这两个方法。 self
调用绑定(bind)到 A
因为它是在 A
的第一个方法的实现中定义的,而 static
绑定(bind)到被调用的类(另见 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
https://stackoverflow.com/questions/5197300/