Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and Classes: access to parent's public property within the parent class

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.

like image 347
Alexar Avatar asked Jan 18 '26 08:01

Alexar


1 Answers

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'];
}
like image 80
Nicolò Martini Avatar answered Jan 20 '26 22:01

Nicolò Martini