Get top level class name when inheritance and clas

2019-09-17 16:53发布

问题:

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?

回答1:

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"


标签: php oop class