Function parameters passed by reference

March 25th, 2005. Tagged: PHP certification

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.

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov