How can I copy an object of another class? How can I copy an object of another class? symfony symfony

How can I copy an object of another class?


try this, Once you instantiate a object, you can't change the class (or other implementation details)

You can simulate it like so:

<?php  class Test  {      private $id;      private $name;      private $age;      private $number;      public function getId() {         return $this->id;      }      public function setId($id) {         $this->id = $id;         return $this;      }      public function getName() {        return $this->name;      }      public function setName($name) {         $this->name = $name;         return $this;      }      public function getAge() {        return $this->age;      }      public function setAge($age) {         $this->age = $age;         return $this;      }      public function getNumber() {        return $this->number;      }      public function setNumber($number) {         $this->number = $number;         return $this;      }      public function toArray()      {         return get_object_vars($this);      }  }  class TestCopy extends Test  {      public $fakeAttribute;  }  function getTestCopy($object)  {    $copy = new TestCopy();    foreach($object->toArray() as $key => $value) {       if(method_exists($copy, 'set'.ucfirst($key))) {          $copy->{'set'.ucfirst($key)}($value);       }    }    return $copy;  }$object = new Test();$object->setId(1);$object->setName('Tom');$object->setAge(20);$object->setNumber(10);$copy = getTestCopy($object);$copy->fakeAttribute = 'fake value';echo "<pre>";print_r($object->toArray());print_r($copy->toArray());

output :

Array(    [id] => 1    [name] => Tom    [age] => 20    [number] => 10)Array(    [fakeAttribute] => fake value    [id] => 1    [name] => Tom    [age] => 20    [number] => 10)