|
home—lects—exams—hws
D2L—breeze (snow day)
In your hw, include a
You can find an example at: lect01b-blend-v7.php.
Looping over arrays:
PHP uses pass-by-value, by default. Here's what that means: When calling a function: All values are written down and handed to the function; the function copies that value into its parameter/variable.
In particular, when you pass an array (or any object), a clone of that entire array is made, and passed. In fact, even when you assign one array to another, a copy is made:
$a = 5; $b = $a; // a *copy* of 5 is made. $x = array(1,2,3,4); $y = $x; // a *copy* of array(1,2,3,4) is made. $y[2] = 99; echo $x[2], " ", $y[2]; function add1ToAll( $data ) { foreach ($data as $k => $val) { $data[$k] += 1; } return $data; } echo "before:" print_r($x); add1ToAll($x); echo "after calling but ignoring return-value:" print_r($x); $x = add1ToAll($x); echo "after calling and re-assigning the return-value:" print_r($x); // Note that there were *three* array-copies happening in `$x = add1ToAll($x)` -- // One to copy the parameter into the function; one copying the return value back, // and one when assigning the return-value (back) into $x. function add1ToAllByReference( &$data ) { foreach ($data as $k => $val) { $data[$k] += 1; } //return $data; // no need to return a passed-by-reference var. } echo "before:" print_r($x); add1ToAll($x); echo "after calling but ignoring return-value:" print_r($x); $x = add1ToAll($x); echo "after calling and re-assigning the return-value:" print_r($x); // Note that there were *three* array-copies happening in `$x = add1ToAll($x)` -- |
This is different from pass-by-reference: In C, when you pass an array to a function, it actually passes a reference to the array — any changes you make to the fields are seen by the caller.
Java uses call-by-value, but object-references are one type of value. (Many people get confused by this, and think that Java passes objects by reference, but it ain't so.) That is, you can pass an int, or a boolean, or a reference-to-String, or reference-to-Puppy.
(example/pictures)
home—lects—exams—hws
D2L—breeze (snow day)
©2012, Ian Barland, Radford University Last modified 2012.Nov.28 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |