Get class name from extended class

2019-02-16 08:32发布

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+)

标签: php oop
3条回答
一纸荒年 Trace。
2楼-- · 2019-02-16 08:33

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楼-- · 2019-02-16 08:53

You can simply use:

get_class($this);
查看更多
混吃等死
4楼-- · 2019-02-16 08:55

Use:

get_class($this);
查看更多
登录 后发表回答