PHP new self和new static的区别
发布时间:2020-07-05 08:06:33
来源:51CTO
阅读:700
作者:xtceetg
abstract class DomainObject{
public static function create(){
return new self();
}
}
class User extends DomainObject{}
class Document extends DomainObject{}
var_dump(Document::create());
结果:Fatal error: Cannot instantiate abstract class DomainObject in......
self 对当前类的静态引用,取决于定义当前方法所在的类。也就是说,这里的self被解析为定义create()的DomainObject,而不是解析为调用self的Document类。abstract class DomainObject{
public static function create(){
return new static();//延迟静态绑定
}
}
class User extends DomainObject{}
class Document extends DomainObject{}
var_dump(Document::create());
结果:
class Document#1 (0) {
}