获取子类名而不通过参数传递值

use*_*413 1 php oop

这个问题很难问,因为它似乎回答了.

我有一个在抽象类中声明的方法parent{},它在子类中得到回应foo{}

这个方法需要当前当前的类名即foo工作,那么如何在不通过参数的情况下获取此名称?

abstract class parent{
  public function init(){
     echo "I am running from class ...."; 
  // I want this to say, that is it running from any class that is extending it. 
  } 
}
Run Code Online (Sandbox Code Playgroud)

这是子类,只能拥有一个用户名;

class foo extends parent{
   echo $this->init(); 
 // I could pass the class name through the argument, but I am looking for other alternatives  
}
Run Code Online (Sandbox Code Playgroud)

sro*_*oes 5

 echo "I am running from class " . get_class($this); 
Run Code Online (Sandbox Code Playgroud)

__CLASS__是声明类(你正在使用它的类),get_class它将获得所提供对象的具体类.因此get_class($this)将返回__CLASS__与其子类相同的值或其中一个.