Passing Arguments by Reference
suggest changeFunction arguments can be passed “By Reference”, allowing the function to modify the variable used outside the function:
function pluralize(&$word)
{
if (substr($word, -1) == 'y') {
$word = substr($word, 0, -1) . 'ies';
} else {
$word .= 's';
}
}
$word = 'Bannana';
pluralize($word);
print $word;
// Bannanas
Objects are not passed by reference. The function receives a copy of the object handle, so it can change that object's properties:
function addOneDay($date)
{
$date->modify('+1 day');
}
$date = new DateTime('2014-02-28');
addOneDay($date);
print $date->format('Y-m-d');
// 2014-03-01
To leave the caller's object unchanged, clone it and modify the copy. Assigning a new value to $date inside addOneDay() would not replace the caller's variable unless the parameter was &$date.
Passing by reference can also be used as an alternative way to return parameters. For example, the socket_getpeername function:
bool socket_getpeername ( resource $socket , string &$address [, int &$port ] )
Since PHP 8.0 $socket is a Socket object, not a resource.
This method actually aims to return the address and port of the peer, but since there are two values to return, it chooses to use reference parameters instead. It can be called like this:
if(!socket_getpeername($socket, $address, $port)) {
throw new RuntimeException(socket_strerror(socket_last_error()));
}
echo "Peer: $address:$port\n";
The variables $address and $port do not need to be defined before. They will:
- be defined as
nullfirst, - then passed to the function with the predefined
nullvalue - then modified in the function
- end up defined as the address and port in the calling context.