Function parameters passed by reference

Consider the following example from the book that is supposed to illustrate how a parameter is passed to a function by reference, not by value.
< ?php
function calc_weeks(&$years) {
$my_years += 10;
return $my_years * 52;
}

$my_years = 28;
echo calc_weeks($my_years);
?>
Something wrong? Yes, the function calc_weeks() is taking $years parameter, passed by reference, but never uses it. Instead, the function uses $my_years, this is probably a typo. And if you run this code with error reporting set to E_ALL, you'll get a notice from the compiler, because we're trying to increment a variable ($my_years += 10;) but without initializing $my_years first.

So the correct way to do the example is
< ?php
function calc_weeks(&$years) {
$years += 10;
return $years * 52;
}

$my_years = 28;
echo calc_weeks($my_years);
?>

In terms of results, the first example will return 520 which is (null + 10) * 52. The second one will return (28 + 10) * 52.

This entry was posted on Friday, March 25th, 2005 and is filed under PHP certification. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


Get notification for future posts: follow me on Twitter or subscribe to my RSS feed

Leave a Reply