4.15.3 Passing by referenceThis is NOT the latest copy of this book; click here for the latest version.
When it comes to references, things get the tiniest bit more complicated - you need to be able to accept parameters by reference and also return values by reference. This is done with the reference operator, &.
Marking a variable as "passed by reference" is done in the function definition, not in the function call. That is:
function multiply(&$num1, &$num2) {
is correct, whereas
$mynum = multiply(&5, &10);
is wrong. This means that if you have a function being used hundreds (thousands?) of times across your project, you only need edit the function definition to make it take variables by reference. Passing by reference is often a good way to make your script shorter and easier to read - the choice is not always driven by performance considerations. Consider this code:
<?php
function square1($number) {
return $number * $number;
}
$val = square1($val);
function square2(&$number) {
$number = $number * $number;
}
square2($val); ?>
The first example passes a copy of $val in, multiplies the copy, then returns the result which is then copied back into $val. The second example passes $val in by reference, and it is modified directly inside the function - hence why square2($val); is all that is required in place of the first example's copying.
One key thing to remember is that a reference is a reference to a variable . If you define a function as accepting a reference to a variable, you cannot pass a constant into it. That is, given our definition of square2(), you cannot call the function using square2(10);, as 10 is not a variable, so it cannot be treated as a reference.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|