在静态方法和继承中使用get_class(PHP)

18
我们有一段代码。
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等也是一样。

有没有办法在不为此添加子类方法的情况下获取子类名称?

2个回答

30

你需要使用 get_called_class 函数,该函数是后期绑定的。但是该函数只能在 PHP 5.3 及以上版本中使用。


2
自 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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接