How do you copy a PHP object into a different object type

后端 未结 5 1824
梦毁少年i
梦毁少年i 2020-12-20 15:50
  1. New class is a subclass of the original object

  2. It needs to be php4 compatible

5条回答
  •  萌比男神i
    2020-12-20 16:34

    You could have your classes instantiated empty and then loaded by any number of methods. One of these methods could accept an instance of the parent class as an argument, and then copy its data from there

    class childClass extends parentClass
    {
        function childClass()
        {
            //do nothing
        }
    
        function loadFromParentObj( $parentObj )
        {
            $this->a = $parentObj->a;
            $this->b = $parentObj->b;
            $this->c = $parentObj->c;
        }
    };
    
    $myParent = new parentClass();
    $myChild = new childClass();
    $myChild->loadFromParentObj( $myParent );
    

提交回复
热议问题