Passing Arguments by Reference

suggest change

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';
pluralize($word);

print $word;
  // Bannanas

Object arguments are always passed by reference:

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Functions:
* Passing Arguments by Reference

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
69 Functions
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR