I've searched for this question and surprisingly didn't find anything about it.
I'm creating dynamically created properties into a parent class and I'm trying to access them in a class child.
This is my code:
class Parent_class {
public $var = '123';
function __set($name, $value){
$this->$name = $value;
}
}
class Child_class extends Parent_class{
}
$parent = new Parent_class();
$child = new Child_class();
$parent->new_property = 'value';
echo $parent->new_property; // returns 'value'
echo $child->var; // returns '123'
echo $child->new_property; // returns 'Notice: Undefined property Child_class::$new_property'
How can I access dynamically created properties in the parent class?
I've managed to get a workaround by using the __get magic method and a static array.
class Parent_class {
public $var = '123';
private static $_global = array();
function __set($name, $value){
self::$_global[$name] = $value;
}
function __get($name){
return self::$_global[$name];
}
}
class Child_class extends Parent_class{
function echoparent(){
return $this->new_property;
}
}
$parent = new Parent_class();
$child = new Child_class();
$parent->new_property = 'value';
echo $parent->new_property; // returns 'value'
echo $child->var; // returns '123'
echo $child->new_property; // returns 'value'
echo $child->echoparent(); // returns 'value'