PHP Passing Arguments by Reference


Function 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';

print $word;
  // Bannanas

Object arguments are always passed by reference:

function addOneDay($date)
    $date->modify('+1 day');

$date = new DateTime('2014-02-28');

print $date->format('Y-m-d');
  // 2014-03-01

To avoid implicit passing an object by reference, you should clone the object.

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 ] )

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_last_error());
echo "Peer: $address:$port\n";

The variables $address and $port do not need to be defined before. They will:

  1. be defined as null first,
  2. then passed to the function with the predefined null value
  3. then modified in the function
  4. end up defined as the address and port in the calling context.