I don't understand the purpose of code snippet

Viewed 62

In Zend Frameword 2.5 a review and saw some code, it works fine but my IDE shows error about it. I don't know purpose of this code snippet. Why to write: $this->table = clone $this->table;

Github Link: https://github.com/zendframework/zend-db/blob/master/src/TableGateway/AbstractTableGateway.php

Function: rows 529-544

Please explain to me about it.

public function __clone()
    {
        $this->resultSetPrototype = (isset($this->resultSetPrototype)) ? clone $this->resultSetPrototype : null;
        $this->sql = clone $this->sql;
        if (is_object($this->table)) {
            $this->table = clone $this->table;
        } elseif (
            is_array($this->table)
            && count($this->table) == 1
            && is_object(reset($this->table))
        ) {
            foreach ($this->table as $alias => &$tableObject) {
                $tableObject = clone $tableObject;
            }
        }
    }
2 Answers

I can't understand Zend purpose but i hope after run two below code snippet, from different two results, you can understand

<?php
class A {
    public $foo = 1;
}  

class B {
    protected $value = 1;
    protected $bar = null;//
    public function __construct() {
      $this->bar = new A();
    }

    public function setValue($foo = 3){
      $this->value = $foo;
    }

    public function setFooBar($foo = 3){
      $this->bar->foo = $foo;
    }

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

$a = new B();
$c = clone($a);
$c->setFooBar(3);
$c->setValue(6);
var_dump($a);
echo "\n";
var_dump($c);
?>
<?php
class A {
    public $foo = 1;
}  

class B {
    protected $value = 1;
    protected $bar = null;//
    public function __construct() {
      $this->bar = new A();
    }

    public function setValue($foo = 3){
      $this->value = $foo;
    }

    public function setFooBar($foo = 3){
      $this->bar->foo = $foo;
    }
}

$a = new B();
$c = clone($a);
$c->setFooBar(3);
$c->setValue(6);
var_dump($a);
echo "\n";
var_dump($c);
?>

clone (or __clone) is a so called magic method. Check for reference on other magic methods the php documentation on magic methods here.
Check also the specific documentation for clone where they explain the working of this magic method:

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.

In other words it allows you to define custom cloning behavior for an object instance inside its class definition using a public __clone method. This method will be called "magically" when you do:

$clone = clone $instance;
Related