Search code examples
zend-framework2

I don't understand the purpose of code snippet


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;
            }
        }
    }

Solution

  • 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);
    ?>