Hudzilla.org - the homepage of Paul Hudson
Contents > Functions > User functions Wish List | Report Bug | About Me ]

4.15.4     Returning by reference

This is NOT the latest copy of this book; click here for the latest version.

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.





<< 4.15.3 Passing by reference   4.15.5 Default parameters >>
Table of Contents
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!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP User - 29 Aug 2008

in the example, the function is probably returning a temporary variable.

function &square1($number) {
return $number * $number;
// wrong, returning ref to temporary variable?
}

its simmilar to this:


function &square1($number) {
$tmp = $number * $number;
return $tmp; // wrong, returning reference to local
}

$val =& square1(10); // val has garbage
unless you can do this:
$val = square1(10); // that would work in c++, in php?
// a solution would be to use a global variable and return a // reference to it

A C++ User - 29 Aug 2008

i reinforce the question made by JMH

in C++ for example, the following would give a compiler error exactly for the reason he exposed

int & square1( int x )
{
int result = x * x;
return result; // warning, returning of local variable
}

Gus Jones - 29 Aug 2008

The best I can do for additional info:

http://www.onlamp.com/pub/a/php/2002/09/12/php_foundations.html

Gus Jones - 29 Aug 2008

"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."

Would be nice to have an example of the above please...

Gogo the Great, Kingstown, Serbia - 29 Aug 2008

In contrast to A PHP User, I find the webmaster@thinking.tk's example pretty useless in explaining the main point of this section.
Furthermore, I really can't get the point of that example. Namely, when I've put the following line immediately before the end of the first PHP block:

var_dump ($Capital);

it has told me that there's only one element in the $Capital array - the one with the key "Nepal" and value "Katmandu".

So, I can't figure out how could this example clarify Paul's statement that "...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..."

I would really appreciate any comments on that!

JMH - 29 Aug 2008

Doesn't variable scope come into play here? In the example above $number only exsits inside the funcion call. Once the function returns, the variable is destroyed.... right? Isn't $val referencing a destroyed variable, in this case, $number?

A PHP User - 29 Aug 2008

11.11.2005, The point is: one good example worth more than 1000 words !! Thanks for doing that webmaster@thinking.tk...

A PHP User - 29 Aug 2008

Thanks for doing that webmaster@thinking.tk...

webmaster@thinking.tk - 29 Aug 2008

<html><head><title>Function Reference</title></head><body>
<table width=50% align=center>
<tr><td>Hello!<br>Make a through study and comment me please.<br>Copy and paste this php code and then run for the desired results. Thanks.</td></tr>

<tr><td bgcolor="#abcdef">
The Capital Cities of the different countries through an array with function reference.<br>
<?php
$Capital["Nepal"]="Kathmandu";
print $Capital["Nepal"];
print "<br>";
function &Ref($n1,$n2){
$Capital["$n1"]="$n2";
return $Capital["$n1"];
}
$s=&Ref("China","Beijing");
print $s;
Print "<br>";
Print $Capital["Nepal"];
Print "<br>";
$s2=&Ref("India","New Deli");
print $s2;
?>
<br>
Every time php access the array without passing through the function there is Kathmandu.
</td></tr>
<tr><td bgcolor="#abcdef">
<p>
But If you pass by reference "g" stands for Glory of Nepal.<br>
<?php
$g="Mt.Everest";
print $g."<br>";

function Ref1(&$g){
$g="Buddha";
return $g;
}
$s1=Ref1(&$g);
print $s1;
Print "<br>";
Print $g;
?>
<br>
But here the glory of Nepal has been permanently changed to Buddha.
</p></td></tr></table></body></html>

A PHP User - 29 Aug 2008

I don't get the point. What is the meaning of this? Could anyone post a practical example illustrating the meaning of returning by reference?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is one plus three?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow