Using & next to operators and functions in PHP

Question:

What is the meaning of using & along with operators and functions in PHP since I've seen this usage in some libraries ( example ) and functions (I'm aware of its use with variables related to passing pointers)

$browser = &new SimpleBrowser();

Answer:

This is the reference operator . It is not very common in PHP. It causes side effects and not everyone is aware of the implications of this. Although the operation is very similar to objects in general which are references by default.

Using this operator you create an alias for a variable. So a variable that receives a reference is actually receiving an address to another variable.

In some cases it can be useful in parameters. It's a way for the code to return extra results since it's normal for a function or method to return just one value. With the reference you can pass a value that will automatically be stored in the place where it originated, that is, in the variable it was in. A change to the function's local parameter will change the variable used to pass it. So it works as a return.

Note that for some types this is normal. Arrays and objects are by reference. The so-called primitive types are what need this operator to change the behavior since the normal of these types is that the values ​​are copied and become independent.

In some cases it can also be useful in iterations:

foreach($obj as $key => &$value)
    $value = 1;

I put it on GitHub for future reference .

By changing the $value variable, you are changing the object's element.

Apparently the use of & new is a legacy from version 4 and should no longer be used. In fact it doesn't make sense to use it because new creates a reference. Nor will I look for better explanations why 4 used this, after all, no one should be using it anymore. The important thing is that now you don't need to. I believe it was forced by OOP in 4 it was pretty hack and started to be part of the language in a minimally decent way in version 5.

Scroll to Top