How to handle __clone for object properties of a child class

When cloning an object that is a child of another object, is it necessary to "specify" all the parent properties that are objects in the method of the child class __clone(), or can the method of the child class __clone()include only its own properties of the object that do not belong to the parent object?

Here is an example

The object Child_Aextends the object Parent_A.

An object Parent_Auses an object A_1in its constructor and has a method __clone().

class Parent_A{

   function __construct(A_1 $a_1){
      $this->A_1 = $a_1;
   }

   function __clone(){
      $this->A_1 = clone $this->A_1;
   }
}

An object Child_Ais required A_2.

class Child_A{

   function __construct(A_2 $a_2){
      parent::__construct(new A_1());

   }

   function __clone(){

      $this->A_2 = clone $this->A_2;
   }
}

If I want to make a deep copy Child_Athat will include deep_copy A_1, should be used in Child_A:

   function __clone(){

      $this->A_1 = clone $this->A_1;
      $this->A_2 = clone $this->A_2;
   }

, A_1:

   function __clone(){

      $this->A_2 = clone $this->A_2;
   }

.

+4
2

, Child_A Parent_A,

class Child_A {

    function __construct(A_2 $a_2){
        parent::__construct(new A_1());
    }
}

.

-, $a_2 , Child_A::__clone undefined A_2.

, - , , parent __clone . , :

class Parent_A
{
    protected $a_1;

    function __construct(A_1 $a_1)
    {
        $this->a_1 = $a_1;
    }

    function __clone()
    {
        $this->a_1 = clone $this->a_1;
    }
}

class Child_A extends Parent_A
{
    protected $a_2;

    function __construct(A_2 $a_2)
    {
        $this->a_2 = $a_2;
        parent::__construct(new A_1);
    }

    function __clone()
    {
        $this->a_2 = clone $this->a_2;
        return parent::__clone();
    }
}
+5

, DeepCopy. , PHPExcel

public function __clone() {
    foreach($this as $key => $val) {
        if (is_object($val) || (is_array($val))) {
            $this->{$key} = unserialize(serialize($val));
        }
    }
}

, DeepCopy.

PHP .

+3

Source: https://habr.com/ru/post/1620033/


All Articles