Passing by reference

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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Returning by reference >>

Previous chapter: Parameters

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.