Get top level class name when inheritance and clas

2019-09-17 16:14发布

I have some classes extended this way:

class Baseresidence extends CActiveRecord {
    public static function model($className=__CLASS__) {
        return parent::model($className); // framework needs, can't modify
    }    
}

class Site1Residence extends Baseresidence {

}

and finally

class_alias('Site1Residence', 'Residence'); // this is part of an autoloader

So in the end I have like this Residence extends Site1Residence extends Baseresidence extends CActiveRecord

In the Baseresidence I have a static method model() which retrieves an instance.

Now I can call::

$r=Residence::model();

The problem is that __CLASS__ constant is used as default value, and that on that level is Baseresidence, and I need there the top level class name (created with the alias) and it should be 'Residence'

if I do:

echo get_class($r); // the Baseresidence is printed

The goal is to print residence

I do not want to pass anything when calling $r=Residence::model(); I would like to resolve it on the roots.

How to get the top level class name on that level?

标签: php oop class
1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-17 16:47

Try

get_called_class();

See http://php.net/manual/en/function.get-called-class.php

From the docs:

class foo {
    static public function test() {
        var_dump(get_called_class());
    }
}

class bar extends foo {
}

foo::test();
bar::test();

The above example will output:

string(3) "foo"
string(3) "bar"
查看更多
登录 后发表回答