PHP:是否可以检索子类的类名?

时间:2009-12-10 23:03:51

标签: php oop

class Bob extends Person
{
    //do some stuff
}

class Person
{
    public function __construct()
    {
        //get the class name of the class that is extending this one
        //should be Bob
    }
}

如何从Bob类的构造函数中获取Person的类名?

4 个答案:

答案 0 :(得分:7)

使用get_class($ this)。

它适用于子类,子子类,父类,一切。就试一试吧! ;)

答案 1 :(得分:3)

class Person
{
  public function __construct()
  {
    echo get_class($this);
  }
}

class Bob extends Person
{
  //do some stuff
}

$b = new Bob;

打印Bob,如“示例#2在超类中使用get_class()”中所述http://docs.php.net/get_class

答案 2 :(得分:2)

class Bob extends Person
{
    //do some stuff
}

class Person
{
    public function __construct()
    {
        var_dump(get_class($this)); // Bob
        var_dump(get_class());      // Person
    }
}

new Bob;

来源:http://www.php.net/manual/en/function.get-class.php

答案 3 :(得分:1)

<?php

class Bob extends Person
{

    public function __construct()
    {
        parent::__construct();
    }

    public function whoAmI()
    {
        echo "Hi! I'm ".__CLASS__.", and my parent is named " , get_parent_class($this) , ".\n";
    }
}

class Person
{
    public function __construct()
    {
        echo "Hello. My name is ".__CLASS__.", and I have a child named " , get_class($this) , ".\n";
    }
}

// Hello. My name is Person, and I have a child named Bob.
$b = new Bob;
// Hi! I'm Bob, and my parent is named Person.
$b->whoAmI();