PHP中new static与new self的区别
在编写代码过程中,可能会遇到使用 new static() 的场景,从而产生疑问:为何不直接使用 new self()?经过查阅资料,明确了两者之间的具体差异。
首先,当存在子类继承关系时,两者的行为表现截然不同。
其次,需要注意的是,PHP 5.2 及更早版本不支持 new static() 的语法特性。
通俗理解,self 代表代码书写所在的类,即定义该方法的那个类;而所谓的后期静态绑定中,static 代表的是当前被调用的类。如果在父类中定义 static,并通过子类间接调用,它指代的便是那个子类。
因此,static 的行为类似于 $this,但它可以用于静态方法和属性等场景,确保引用的是实际触发调用的类。
具体解释如下:
self 指的是代码段所在的那个类,即定义该方法的类本身。
static 是 PHP 5.3 引入的概念,指代当前被调用的类。它类似于 $this,从堆内存中提取出当前实例化的类,访问的是实际调用该方法的类,因此 static 代表的就是那个被调用的类。
参考国外专家的专业解释:
self refers to the same class whose method the new operation takes place in.
static in PHP 5.3's late static bindings refers to whatever class in the hierarchy which you call the method on.
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 Person {
public static function get_self() {
return new self();
}
public static function get_static() {
return new static();
}
}
class WangBaoqiang extends Person{}
echo get_class(WangBaoqiang::get_self()); // Person
echo get_class(WangBaoqiang::get_static()); // WangBaoqiang
echo get_class(Person::get_static()); // Person
但是如果想让 子类使用 get_class时,返回的也是 当前子类的名称('wangbaoqiang'),该怎么做呢。
<?php
class Person {
public function create1() {
$class = get_class($this);
return new $class();
}
public function create2() {
return new static();
}
}
class WangBaoqiang extends Person {
}
$wangBaoQiang = new WangBaoqiang();
var_dump(get_class($wangBaoQiang->create1()), get_class($wangBaoQiang->create2()));
/*
The result
string(1) "WangBaoqiang"
string(1) "WangBaoqiang"
*/
以上所述是小编给大家介绍的PHP中new static()与new self()的比较,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对本站网站的支持!