开发者

assign object to array

开发者 https://www.devze.com 2023-02-01 08:50 出处:网络
$var[1] = new Base(); $var[2] =& $var[1]; Will it make any difference to my script if I use $var[2] = $var[1]; instead of $var[2] =& $var[1];
$var[1] = new Base();
$var[2] =& $var[1];

Will it make any difference to my script if I use $var[2] = $var[1]; instead of $var[2] =& $var[1];

As it will eventually pass refrence to $var[2] when i w开发者_Python百科rite $var[2] = $var[1];


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

Will assign a reference of the second array element (not the value) to the third element:

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

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

prints

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

I think you only want both entries point to the same object and as objects are passed by reference, $var[2] = $var[1]; is the correct way:

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

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

prints

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

and if you do $var[1] = 'foo' afterwards it gives you:

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


You can understand by an example

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

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

let take another example

$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";

output is a c

0

精彩评论

暂无评论...
验证码 换一张
取 消