将对象分配给数组

时间:2010-12-29 12:17:12

标签: php

$var[1] = new Base();
$var[2] =& $var[1];

如果我使用$var[2] = $var[1];代替$var[2] =& $var[1];

,我的脚本会有什么不同吗?

当我写$var[2] = $var[1];

时,它最终会将引用传递给$ var [2]

2 个答案:

答案 0 :(得分:2)

$var[2] =& $var[1];

将第二个数组元素(不是值)的引用分配给第三个元素:

class Base{};
$var[1] = new Base();
$var[2] =& $var[1];

$var[1] = 'foo';
var_dump($var);

打印

array(2) {
  [1]=>
  &string(3) "foo"
  [2]=>
  &string(3) "foo"
}

我认为您只希望两个条目指向同一个对象,并且对象通过引用传递,$var[2] = $var[1];是正确的方法:

class Base{};
$var[1] = new Base();
$var[2] = $var[1];

$var[1]->foo = 'bar';
var_dump($var);

打印

array(2) {
  [1]=>
  object(Base)#1 (1) {
    ["foo"]=>
    string(3) "bar"
  }
  [2]=>
  object(Base)#1 (1) {
    ["foo"]=>
    string(3) "bar"
  }
}

如果你事后$var[1] = 'foo'它会给你:

array(2) {
  [1]=>
  string(3) "foo"
  [2]=>
  object(Base)#1 (1) {
    ["foo"]=>
    string(3) "bar"
  }
}

答案 1 :(得分:1)

您可以通过示例理解

   $value1 = "Hello";
   $value2 =& $value1; /* $value1 and $value2 both equal "Hello". */
   $value2 = "Goodbye"; /* $value1 and $value2 both equal "Goodbye". */

   echo($value1);
   echo($value2);

让我们再看一个例子

$a = array('a'=>'a');
$b = $a; // $b is a copy of $a
$c = & $a; // $c is a reference of $a
$b['a'] = 'b'; // $a not changed
echo $a['a'], "\n";
$c['a'] = 'c'; // $a changed
echo $a['a'], "\n";

输出是c