Monday, April 28, 2008

Some examples on how to use call-by-reference in PHP

Some examples on how to use call-by-reference in PHP

Whilst passing variables by copy is OK for most basic tasks, passing variables by reference is very useful when it comes to advanced data structures such as lists and trees.

PHP supports passing references using the & operator, but it can be a bit painful to work out what's going on, especially once you start trying to store references to objects in arrays, and then try to iterate over them.

So here goes...


$a=5; print("A=$a.");
A=5.

Introducing references...


$a=5; $a_ptr=&$a; print("A=$a."); $a_ptr=6; print("A=$a.");
A=5.A=6.

Introducing arrays...


$a=5; $b=50; $arr=array(&$a,&$b); print("A=$a, B=$b. "); $arr[0]=6; print("A=$a, B=$b. ");
A=5, B=50. A=6, B=50.

For each'ing...

This does not work as intended, because 'foreach' creates copies of the array elements. Changes made to those copies get lost after the loop body.
$a=5; $b=50; $arr=array(&$a,&$b); print("A=$a, B=$b. "); foreach( $arr as $x ) { $x=$x+1; print( "now $x. " ); } print("A=$a, B=$b. ");
A=5, B=50. now 6. now 51. A=5, B=50.

Replacement for 'for each' that works like references...

This will work with arrays of objects as well, of course. In that case, "$arr[$key]=$arr[$key]+1" will need to be replaced with something along the lines of "$arr[$key]->someFunction()".
$a=5; $b=50; $arr=array(&$a,&$b); print("A=$a, B=$b. "); foreach (array_keys($arr) as $key) { $arr[$key]=$arr[$key]+1; print( "now $arr[$key]. " ); } print("A=$a, B=$b. ");
A=5, B=50. now 6. now 51. A=6, B=51.
The end.

Bibliography

No comments:

Post a Comment