PHP 和类 : access to parent's public property within the parent class

标签 php class object parent

我的代码是这样的

我有两种形式:

class Form_1 extends Form_Abstract {

    public $iId = 1;

}
class Form_2 extends Form_1 {

    public $iId = 2;

}

我希望代码的行为是这样的:

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

这是我的 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;
    }
}

但它抛出一个 fatal error :

Fatal error: Cannot access parent:: when current class scope has no parent

请帮助我使用方法getParentId()

PS:我知道发生这种情况的原因,我正在寻求解决方案。

最佳答案

您必须使用Reflection Api 来访问父类的属性默认值。用这个替换 Form_Abstract 中的 getParentId,一切正常:

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

    return $def_props['iId'];
}

显然您不能在根类中调用 getParentId(),因此最好检查父类是否存在。

更新:

你可以对类/对象函数做同样的事情:

public function getParentId() {
    $def_values = get_class_vars(get_parent_class($this));
    return $def_values['iId'];
}

关于PHP 和类 : access to parent's public property within the parent class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2439181/

相关文章:

python - 在 Django 中通过 self.request.user 过滤对象列表

javascript - 使用 Vue.JS 编辑数组对象

C#类属性,通过索引获取

javascript - 遍历对象数组并根据条件添加到其他数组

Python 文件对象允许您关闭已经关闭的文件

php - Codeigniter 分页 - 我很难过

php - Google API 如何连接以从电子表格接收值

php - 检查字符串是否包含数组中的单词

php - 如何按 "natural"顺序正确对数据库中的项目进行排序

jquery 变量作为 div ID 或类