Returning References from Functions


Besides passing values by reference, you can also return references from functions, which you might want to do if you need to move references around your code while processing them. (This is not something you'll be using every day, so feel free to skip to the next chunk.) References point to the same location in memory. For example, if you set $value to 5, you could create a reference to that variable with this syntax:

 $value = 5; $ref = & $value; 

Now $ref is a reference to $value, and it will point to the same data in memory as $valuechanging one changes the other.

Here's how returning references from a function works. We'll create a function that will take a reference and just return that reference, like this:

 function &return_a_reference(& $reference) {     return $reference; } 

Note the syntax here; this function returns a reference, so you use & in front of its name when creating it.

You also use & when getting the return value from a function that returns a reference, like the following, where we recover the reference to $value passed to the function and use it to increment the value in $value:

 $value = 5; echo "Old value: ", $value, "\n"; $ref =& return_a_reference($value); $ref++; echo "New value: ", $value, "\n"; function &return_a_reference(& $reference) {     return $reference; } 

And here's what you seewe were able to increment $value by incrementing the reference to that variable:

 Old value: 5 New value: 6 



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net