I have a parent class A, and child class B in PHP. Is there any way to clone instance of class A to instance of B, and to use B class properties later in B instance? Thanks
Asked
Active
Viewed 6,826 times
20
-
1http://php.net/manual/en/language.oop5.cloning.php – davidkonrad Oct 14 '12 at 12:42
-
1I don't think you can extend instances in real time if that is what you are asking. Consider giving more details about what you are trying to do though, perhaps there is another way. – Mahn Oct 14 '12 at 12:47
-
Does this answer your question? [How do you copy a PHP object into a different object type](https://stackoverflow.com/questions/119281/how-do-you-copy-a-php-object-into-a-different-object-type) – Melebius Jul 07 '22 at 06:37
1 Answers
25
My solution will be based on the solution from this question How do you copy a PHP object into a different object type
class childClass extends parentClass
{
private $a;
private $b;
function loadFromParentObj( $parentObj )
{
$objValues = get_object_vars($parentObj); // return array of object values
foreach($objValues AS $key=>$value)
{
$this->$key = $value;
}
}
}
$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );