[英]get_class in static method and inheritance (php)
我们有一个代码
class ParentClass {
public static function getName() {
return get_class(self);
}
}
class ChildClass extends ParentClass {
}
echo ParentClass::getName(); # => 'ParentClass'
echo ChildClass::getName(); # => 'ParentClass'
如果我使用 get_class($this) 有相同的结果。 也适用于 self::$this、static::$this 等
有什么方法可以在不为此向子类添加方法的情况下获取子类名称?
您必须使用get_called_class
,它绑定较晚。 仅自 PHP 5.3 起可用。
从 PHP 5.5 开始,我们可以使用static::class
而不是get_called_class
:
class ParentClass {
public static function getName() {
return static::class;
}
}
class ChildClass extends ParentClass {
}
echo ParentClass::getName(); # => 'ParentClass'
echo ChildClass::getName(); # => 'ChildClass'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.