PHP中new static()与new self()的区别异同分析
本内容深入剖析了PHP语言中new static()与new self()这两个关键字的异同点,旨在为PHP程序员的日常开发提供实用的参考与帮助。
起因是在本地环境搭建网站时遇到障碍,由于项目代码中包含大量PHP 5.3及以上版本的特性,导致无法在PHP 5.2环境下正常运行,因此需要进行兼容性改造。
在逐步修改代码的过程中,发现了一处关键的语法差异。
return new static($val);
此处使用了之前未曾见过的语法结构。
return new self($val);
为了弄清楚原因,查阅了相关资料以明确两者的具体区别。
self关键字代表的是当前代码段所在的类,即定义该方法的那个类本身。
static是PHP 5.3版本引入的特性,意为“当前类”,类似于$this的概念,但它从堆内存中提取并访问当前被实例化的那个类,此时static代表的就是那个具体的类。
参考国外技术文档的专业解释可以更清晰地理解其机制:
self指的是执行new操作的方法所在的那个类。
在PHP 5.3的晚期静态绑定(late static bindings)机制下,static指的是调用该方法时层级结构中的那个类。
In the following example, B inherits both methods from A. self 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_static()); // A
通过这个例子,应该能直观地理解两者的运行逻辑。
虽然理解了原理,但实际问题仍未解决,如何消除return new static($val);这一行代码带来的兼容性问题呢?
解决方法其实很简单,可以使用get_class($this);来实现,具体代码如下:
class A {
public function create1() {
$class = get_class($this);
return new $class();
}
public function create2() {
return new static();
}
}
class B extends A {
}
$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));
/*
The result
string(1) "B"
string(1) "B"
*/
感兴趣的读者可以动手测试上述示例代码,相信会有新的收获!