0

再会。遇到了一个看起来像这样的问题:我有一个变量,它在循环中被重置并重新填充。我将该变量分配给其他变量,因为它是属性(如 $item->subitems)。例如,我将 $item 收集到 $item 数组中。每个循环都会重新设置和重新填充此变量,并包含不同的数据。近似的示例代码如下:

<?php
$seasons = array(1,2);
$ltabs= array(1);
$all = array(1,2,3,4,5,6,7,8,9,0);
        foreach ($ltabs as $tab)
        {
            //Resetting an object instance
            $itm=false;
            //Re-Initing object
            if (1==1)
            {
                $itm->height = 1;
                $itm->width  = 2;
            }
            else
            {
                $itm->height = 3;
                $itm->width  = 4;
            }
            //And thats where crap happens
            //foreach($seasons as $season) //Dont work that way too
            for ($y=0;$y<count($seasons);$y++)
            {
                //Re-initing local array for needed values
                $itemz=array();
                //$itm->items = array();
                for($a=0;$a < count($all);$a++) {
                    if ($all[$a] % $seasons)//Not tested, supposed to gove ANY dofference in arrays. 
                    {
                        $itemz[]=$all[$a];
                    }
                 }
                $itm->items = $itemz;
                $rtabs[$season] = $itm;
                unset($itemz);
                //unset($itemz);
            }
        }
        //Returns crap.
        var_dump($rtabs);
?>

但是当我尝试

<?php
foreach($rtabs as $itm)
{
    var_dump($itm->items);
}
?>  

我看到所有这些子项都包含相同的数据集。我只能通过在这个子循环中重新分配整个 $itm 变量来成功地击败它。但我想不明白 - 为什么它会那样做?.. 根据这篇文章 - 当我重置这个 $itemz 数组时,垃圾收集器和 php 的写时复制的东西应该被初始化,所以对我来说这一切看起来很不合逻辑。任何帮助,将不胜感激。

4

1 回答 1

2

在 php 中,对象是通过引用复制的,所以在这一行:

$rtabs[$season] = $itm;

您没有将$itm对象的副本放入数组中 - 您正在复制对它的引用。当您稍后更改原始对象时,rtabs数组中的版本也会更改。

如果你想制作一个单独的副本,你需要做这样的事情。

$rtabs[$season] = clone $itm;
于 2013-05-12T00:14:53.567 回答