start page | rating of books | rating of authors | reviews | copyrights

Programming PHPProgramming PHPSearch this book

3.5. Return Values

PHP functions can return only a single value with the return keyword:

function return_one() {
   return 42;
}

To return multiple values, return an array:

function return_two ( ) {
   return array("Fred", 35);
}

By default, values are copied out of the function. A function declared with an & before its name returns a reference (alias) to its return value:

$names = array("Fred", "Barney", "Wilma", "Betty");
function & find_one($n) {
   return $names[$n];
}
$person =& find_one(1);           // Barney
$person = "Barnetta";             // changes $names[1]

In this code, the find_one( ) function returns an alias for $names[1], instead of a copy of its value. Because we assign by reference, $person is an alias for $names[1], and the second assignment changes the value in $names[1].

This technique is sometimes used to return large string or array values efficiently from a function. However, PHP's copy-on-write/shallow-copy mechanism usually means that returning a reference from a function is not necessary. There is no point in returning a reference to some large piece of data unless you know you are likely to change that data. The drawback of returning the reference is that it is slower than returning the value and relying on the shallow-copy mechanism to ensure that a copy of that data is not made unless it is changed.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.