Get class name from extended class

2019-02-16 08:08发布

问题:

Is it possible to get the name of the top level class from an extended class, without setting it from the top level class. See example below, I would like to get 'Foo' from Base. I know I could set a variable from Foo, but hoping to skip the extra step.

Thanks.

class Base {

    function __construct() {

        echo '<p>get_class: '.get_class().'</p>';
        echo '<p>__CLASS__: '.__CLASS__.'</p>';

    }

}


class Foo extends Base {

}


$test = new Foo();

(PHP 5.2.4+)

回答1:

Use:

get_class($this);


回答2:

get_called_class() for static classes or get_class($this) for instantiated.

get_called_class(), as Jason said, was introduced in PHP 5.3



回答3:

You can simply use:

get_class($this);


标签: php oop