duanbozhong9689 2010-03-13 17:06
浏览 250
已采纳

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

here is what my code looks like

i have two forms:

class Form_1 extends Form_Abstract {

    public $iId = 1;

}
class Form_2 extends Form_1 {

    public $iId = 2;

}

i expect the code behave like this:

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

here is my Form_Abstract class:

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;
    }
}

but it throws a Fatal Error:

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

please help me with the method getParentId()

PS: i know the reason of what happens, i am seeking for the solution.

  • 写回答

4条回答 默认 最新

  • douba1067 2010-03-13 17:37
    关注

    You have to use Reflection Api to access the parent class' property default value. Substitute getParentId, in Form_Abstract, with this, and all works fine:

    public function getParentId() {
        $refclass = new ReflectionClass($this);
        $refparent = $refclass->getParentClass();
        $def_props = $refparent->getDefaultProperties();
    
        return $def_props['iId'];
    }
    

    Clearly you cannot call getParentId() in the root class, so it's better to check if a parent class exists.

    UDATE:

    You can do the same with classes/objects functions:

    public function getParentId() {
        $def_values = get_class_vars(get_parent_class($this));
        return $def_values['iId'];
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题