PHP assign by reference

See codes below:

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

The output is:

a
c

Also, we know that when we use [] to get a data from an array, this return the reference to the internal data. So it we pass in a reference of data to array, and then we get the data from the array. This operation will change the original data.

See below:

$a = array('a'=>'a');
$b = array();
$b[] = $a;
$b[] = & $a;
$b[0]['a'] = 'b';
echo $a['a'],"\n";
$b[1]['a'] = 'c';
echo $a['a'], "\n";

output is:

a
c
Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Share/Bookmark

Leave a Reply