134
votes

I'm using the Facebook library with this code in it:

class FacebookRestClient {
...
    public function &users_hasAppPermission($ext_perm, $uid=null) {
        return $this->call_method('facebook.users.hasAppPermission', 
        array('ext_perm' => $ext_perm, 'uid' => $uid));
    }
...
}

What does the & at the beginning of the function definition mean, and how do I go about using a library like this (in a simple example)

3

3 Answers

162
votes

An ampersand before a function name means the function will return a reference to a variable instead of the value.

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not 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.

See Returning References.

17
votes

It's returning a reference, as mentioned already. In PHP 4, objects were assigned by value, just like any other value. This is highly unintuitive and contrary to how most other languages works.

To get around the problem, references were used for variables that pointed to objects. In PHP 5, references are very rarely used. I'm guessing this is legacy code or code trying to preserve backwards compatibility with PHP 4.

5
votes

This is often known in PHP as Returning reference or Returning by reference.

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not 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.

PHP documentation on Returning reference

A reference in PHP is simply another name assigned to the content of a variable. PHP references are not like pointers in C programming, they are not actual memory addresses, so they cannot be used for pointer arithmetics.

The concept of returning references can be very confusing especially to beginners, so an example will be helpful.

$populationCount = 120;

function &getPopulationCount() {
  global $populationCount;
  return $populationCount;
}

$countryPopulation =& getPopulationCount();
$countryPopulation++;
echo "\$populationCount = $populationCount\n"; // Output: $populationCount = 121 
echo "\$countryPopulation = $countryPopulation\n"; //Output: $countryPopulation = 121 

The function getPopulationCount() defined with a preceding &, returns the reference to the content or value of $populationCount. So, incrementing $countryPopulation, also increments $populationCount.