开发者

PHP: Is it possible to retrieve the class name of a child class?

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
    }
}

How can I get the class name of Bob from inside 开发者_StackOverflow中文版the constructor of the Person class?


Use get_class($this).

It works for sub-class, sub-sub-class, the parent class, everything. Just try it! ;)


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

class Bob extends Person
{
  //do some stuff
}

$b = new Bob;

prints Bob as explained in "Example #2 Using get_class() in superclass" at http://docs.php.net/get_class


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;

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


<?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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜