PHP和类:访问父类中父项的公共属性

Ale*_*xar 2 php class object parent

这是我的代码的样子

我有两种形式:

class Form_1 extends Form_Abstract {

    public $iId = 1;

}
class Form_2 extends Form_1 {

    public $iId = 2;

}
Run Code Online (Sandbox Code Playgroud)

我希望代码的行为如下:

$oForm = new Form_2;
echo $oForm->getId(); // it returns '2'
echo $oForm->getParentId(); // i expect it returns '1'
Run Code Online (Sandbox Code Playgroud)

这是我的Form_Abstract类:

class Form_Abstract {

    public $iId = 0;

    public function getId() {
        return $this->iId;
    }

/**
this method will be called from a child instance
*/
    public function getParentId() {
        return parent::$iId;
    }
}
Run Code Online (Sandbox Code Playgroud)

但它会引发致命错误:

Fatal error: Cannot access parent:: when current class scope has no parent
Run Code Online (Sandbox Code Playgroud)

请帮我解决这个问题 getParentId()

PS:我知道发生了什么的原因,我正在寻求解决方案.

Nic*_*ini 5

您必须使用Reflection Api来访问父类的属性默认值.Form_Abstract使用此替换getParentId,并且一切正常:

public function getParentId() {
    $refclass = new ReflectionClass($this);
    $refparent = $refclass->getParentClass();
    $def_props = $refparent->getDefaultProperties();

    return $def_props['iId'];
}
Run Code Online (Sandbox Code Playgroud)

显然,您无法在根类中调用getParentId(),因此最好检查父类是否存在.

UDATE:

您可以对类/对象函数执行相同的操作:

public function getParentId() {
    $def_values = get_class_vars(get_parent_class($this));
    return $def_values['iId'];
}
Run Code Online (Sandbox Code Playgroud)