【问题标题】:Why is the PHP assignment operator acting as an assignment by reference in this case?在这种情况下,为什么 PHP 赋值运算符充当引用赋值?
【发布时间】:2011-01-16 04:12:33
【问题描述】:

我有一些代码在 PHP 4 和 PHP 5 之间的行为似乎不同。以下代码:

class CFoo
{
    var $arr;

    function CFoo()
    {
        $this->arr = array();
    }

    function AddToArray($i)
    {
        $this->arr[] = $i;
    }

    function DoStuffOnFoo()
    {
        for ($i = 0; $i < 10; ++$i)
        {
            $foo2 = new CFoo();
            $foo2 = $this;          // I expect this to copy, therefore
                                    // resetting back to the original $this
            $foo2->AddToArray($i);
            echo "Foo2:\n";
            print_r($foo2);
            echo "This:\n";
            print_r($this);
        }
    }
}

$foo1 = new CFoo();
$foo1->DoStuffOnFoo();

以前,在 PHP 4 中,上面对 $foo2 的赋值会将 $foo2 重置为 $this 最初设置的值。在这种情况下,我希望它被设置为具有空 $arr 成员的 CFoo。但是,$foo2 对 $this 的赋值是作为引用赋值。 Foo2 是这个的别名。因此,当我在 foo2 上调用“AddToArray”时,$this 的 $arr 也被附加到。因此,当我将 foo2 重新分配回 this 时,我并没有得到 this 的初始值,而是得到了一个自赋值。

这种行为在 PHP 5 中是否有所改变?我能做些什么来强制 foo2 复制这个?

【问题讨论】:

    标签: php variable-assignment php4 assignment-operator


    【解决方案1】:

    是的,PHP 5 现在正在通过引用进行复制。现在您必须 clone 复制该对象。

    【讨论】:

      【解决方案2】:

      PHP 从版本 5 开始使用引用。要复制对象,请使用:

      $copy = clone $object;
      

      【讨论】:

        【解决方案3】:

        在 PHP 4 中,除非您通过引用(使用 &=)分配对象,否则会复制对象。在 PHP 5 中分配了对该对象的引用。

        所以在将$this 分配给$foo2 之后,$foo2 指向$this 而不是CFoo 的新副本。

        要在 PHP 5 中复制,请输入 clone $this。

        在任何一种情况下,前面的new 语句都被浪费了。

        【讨论】:

          【解决方案4】:

          PHP 的面向对象部分已经非常大了overhauled in PHP 5。对象现在作为引用传递 (not exactly but almost)。见http://docs.php.net/clone。

          例子:

          $x1 = new StdClass;
          $x1->a = 'x1a';
          
          $x2 = $x1;
          $y = clone $x1;
          
          // Performing operations on x2 affects x1 / same underlying object
          $x2->a = 'x2A';
          $x2->b = 'x2B';
          
          // y is a clone / changes do not affect x1
          $y->b = 'yB';
          
          echo 'x1: '; print_r($x1);
          echo 'y:'; print_r($y);
          

          打印

          x1: stdClass Object
          (
              [a] => x2A
              [b] => x2B
          )
          y:stdClass Object
          (
              [a] => x1a
              [b] => yB
          )
          

          【讨论】:

            猜你喜欢
            • 2019-12-04
            • 2012-11-02
            • 2013-08-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-12-15
            • 1970-01-01
            • 2010-12-18
            相关资源
            最近更新 更多