如何知道在继承类上调用方法的类?

时间:2015-08-31 01:26:51

标签: php inheritance

我想知道正在调用方法的类的名称。

例如:

class Mother{
  static function foo(){
    return "Who call me";
  }
}

class Son extends Mother{ }

class OtherSon extends Mother{ }


Son::foo();
>> Son

OtherSon::foo();
>> Other Son

怎么做?

1 个答案:

答案 0 :(得分:1)

使用get_called_class()找到解决方案:

class Mother{
  static function foo(){
    echo get_class(),PHP_EOL;
    echo __CLASS__,PHP_EOL;
    echo get_called_class(),PHP_EOL;
  }

}

class Son1 extends Mother {}
class Son2 extends Mother {}

Son1::foo();
Son2::foo();

返回:

Mother
Mother
Son1
Mother
Mother
Son2

因此,您可以看到get_class__CLASS__都返回Mother,但使用get_called_class()将返回调用该函数的类!

如果使用php> = 5.5

,您似乎还可以使用static::class返回相同内容
相关问题