0
$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 write $var[2] = $var[1];

1
  • any reason not doing this ? $var[1] = $var[2] = new Base(); ? Commented Dec 29, 2010 at 12:21

2 Answers 2

2
$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"
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Thanks for reply. What you have explained is true for array and variable. But my question is for class and its object. how will it behave in case of object assignment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.