Returning References
Returning References
Returning by reference is useful when you want to use a function
to find to which variable a reference should be bound. Do
use return-by-reference to increase performance.
The engine will automatically optimize this on its own. Only return
references when you have a valid technical reason to do so. To
return references, use this syntax:
In this example, the property of the object returned by the
function would be set, not the
copy, as it would be without using reference syntax.
not```php
value; } } $obj = new Foo(); $myValue = &$obj->getValue(); // $myValue is a reference to $obj->value, which is 42 $obj->value = 2; echo $myValue; // Prints the new value of $obj->value, i.e. 2 ?>
`getValue`
> **Opmerking:** > Unlike parameter passing, here you have to use
> in both places - to indicate that you
> want to return by reference, not a copy, and to indicate that
> reference binding, rather than usual assignment, should be done
> for .
> `&``$myValue`
> **Opmerking:** > If you try to return a reference from a function with the syntax:
> this will
> work as you are attempting to return the result of an
> , and not a variable, by reference. You can
> only return variables by reference from a function - nothing else.
> `return ($this->value);`*not**expression*
To use the returned reference, you must use reference assignment:
To pass the returned reference to another function expecting a reference
you can use this syntax:
```php
<?php
function &collector()
{
static $collection = array();
return $collection;
}
$collection = &collector();
// Now the $collection is a referenced variable that references the static array inside the function
$collection[] = 'foo';
print_r(collector());
// Array
// (
// [0] => foo
// )
?>
Opmerking: > If the assignment is done without the symbol, e.g. , the variable will receive a copy of the value, not the reference returned by the function.
&``$collection = collector();``$collection
<?php
function &collector()
{
static $collection = array();
return $collection;
}
array_push(collector(), 'foo');
?>
Opmerking: > Note that will work, it results in a fatal error.
array_push(&collector(), 'foo');not