Returning by reference

A final important thing to know about user functions and references is how to return values by reference. Unlike passing values by reference where you just specify the referenced nature of the parameter in the function definition, to properly return references you need to specify in the definition and at call time. To specify a function returns a reference, you place the ampersand reference operator before the function name, and to specify that you wish to reference the result of the function as opposed to copying it, you use the normal reference assign that you learnt earlier.

Here's how that looks:

<?php
    function &square1($number) {
        return $number * $number;
    }

    $val =& square1(10);
?>

In that example we do not pass any parameters in by reference, but we do pass back and assign a reference. With that code, you could remove the references entirely and it would still do exactly the same thing. However, the ability to return references becomes more important if, say, you were to return an element in an array - with references, you could change the element that gets returned, and it would change the array; without, you would get a copy of the element back, and any changes you made would not be reflected in the original.

 

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: Default parameters >>

Previous chapter: Passing by reference

Jump to:

 

Home: Table of Contents

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