I have a method which creates an instance of a child class and copies its properties over. I achieve this with $child->property = $this(parent)->propery
with each property. Is there a way to do this all in one bite without having to repeat the code to define each individual property?
Extended example:
class parent {
public $foo
$bar
$gib
public function foobar() {
$child = new child;
$child->foo = $this->foo;
$child->bar = $this->bar;
$child->gib = $this->gib;
}
}
class child extends parent {
}
You are defeating the purpose of inheritance by putting the logic of the child constructor inside the parent. You don't want the parent class to ever have visibility on what the type of the child is.
Consider the following code.
class Parent {
protected $foo;
protected $bar;
public function __construct($foo, $bar) {
$this->foo = $foo;
$this->bar = $bar;
}
}
class Child extends Parent {
public function __construct($foo, $bar) {
parent::__construct($foo, $bar);
}
}
Here, the child takes it upon itself to instantiate the properties of the parent class. It is the responsibility of the child class to do so.
Related reading - http://www.php.net//manual/en/language.oop5.decon.php
You could package up your parent objects variables in an associative array and use a foreach loop to iterate over the variables back to the child object. Might be faster if you have a lot of variables.
EDIT: The idea of this being this is a dictionary where the keys are variable names and values are the actual variable.