20

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

MMiroslav
  • 1,672
  • 20
  • 32
  • 1
    http://php.net/manual/en/language.oop5.cloning.php – davidkonrad Oct 14 '12 at 12:42
  • 1
    I 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 Answers1

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 );
Community
  • 1
  • 1
Oras
  • 1,036
  • 1
  • 12
  • 18