首页 > 解决方案 > 我不明白代码片段的目的

问题描述

在 Zend Frameword 2.5 中查看并看到了一些代码,它工作正常,但我的 IDE 显示错误。我不知道这个代码片段的目的。为什么要写:$this->table = clone $this->table;

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

功能:第 529-544 行

请向我解释一下。

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

标签: zend-framework2

解决方案


我无法理解 Zend 的目的,但我希望在运行以下两个代码片段后,从不同的两个结果中,你可以理解

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

推荐阅读