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:

function &square1($number) {
$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.


Next chapter: Default parameters >>

Previous chapter: Passing by reference

Jump to:


Home: Table of Contents

Follow us on or Twitter

Username:   Password:
Create Account | About TuxRadar