Use of & along with Operators and Functions in PHP

11

What is the meaning of using & with operators and functions in PHP since I checked in some libraries Example and functions this use (I am aware of the use next to variables has relation to the passing of pointers)

$browser = &new SimpleBrowser();
    
asked by anonymous 19.02.2015 / 12:57

4 answers

10

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

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

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

Note that some types this is normal. Arrays and objects are by reference. The so-called primitive types are that they 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;

In this way changing the variable $value you are changing the element of the object.

Apparently the use of & new is a legacy of version 4 and should no longer be used. In fact it does not make sense to use it because new creates a reference. Nor am I going to look for better explanations because the 4th used this, after all no one should be using it anymore. The important thing is that now does not need more. I think I was obliged by OOP in 4 was very gambiarra and started to be part of the language in a minimally decent way in version 5.

    
19.02.2015 / 13:05
5

This is the Refresh Operator .

According to PHP

  

References, in PHP, means accessing the same variable content across multiple names

See an example:

$a = 1;

$b = $a;

$a = 2;

var_dump($a, $b); // a => 2, b => 1

Now an example with the reference operator:

$a = 1
$b =& $a;
$a = 2;

var_dump($a, $b)/ // a= > 2, b => 2

That is, $b points to the value of $a . It does not have an independent value, but it points to the memory location where the value of $a has been saved.

In the case of functions, the & operator can be used in two ways:

I'll give you an example of passing by reference in functions:

$meuValor = [1, 2, 3];

    function my_function(&$var, $add){
       $var[] = $add;
    }

    my_function($meuValor, 6);

    print_($meuValor); // [1, 2, 3, 6];

Notice that the value of $meuValor has been changed, without the return within the function and without the reassignment of it by the return of my_function .

This happens because $var passes the reference of the variable passed by parameter; that is, the variable $meuValor .

The use of the new operator has been discouraged, and if I am not mistaken, it generates a E_STRICT error when trying to do it.

This was in versions prior to PHP 5.

In new versions of PHP, objects are passed by reference by default.

    
19.02.2015 / 13:04
4

The & operator has some functions currently used as reference operator as both answers explains well and is also used in anonymous functions.

The example of the link is quite peculiar, it is inheritance of php4 where the support ( adaptation ) to object orientation began a series of things had no implications such as all members of the class being public and & = . Examples have been taken from the old manual session Classes and Objects (PHP 4) > References inside the constructor

Example , run in php4 in other versions.

<?php
class Foo {
    function Foo($name) {
        // create a reference inside the global array $globalref
        global $globalref;//<--- variável global WTF que tenta exemplicar a diferença
        //do new e do &=
        $globalref[] = &$this;
        // set name to passed value
        $this->setName($name);
        // and put it out
        $this->echoName();
    }

    function echoName() {
        echo "<br />", $this->name;
    }

    function setName($name) {
        $this->name = $name;
    }
}
?>

The code below attempts to demonstrate the new usage that only returns a copy of the object and its variables and the & = that returns the reference, which in kids means that some assignments may not 'synchronize' variable / members of the class / gambiarra as 'expected'.

Example 1

Here it shows that everything is ok the 'expected' behavior happens because no modification has been made.

<?php
$bar1 = new Foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */

$bar2 =& new Foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */
?> 

Example 2

Here it shows the difference that $this->name and $globalref[0] in $bar1 are not the same thing because the value was copied, while $bar2 are the same because because of the reference operator & = .

<?php
// now we will change the name. what do you expect?
// you could expect that both $bar1 and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set from outside
set in constructor */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equal, they are the same variable
// thus $bar2->name and $globalref[1]->name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */
?> 
    
19.02.2015 / 15:01
0

This is a reference operator that allows instead of working with the value of the variable to work with your address, see example below:

<?php
   $a = &$b;
   // aqui $a e $b apontam para a mesma variável. 
?>

So, $ a and $ b go here because $ a and $ b point to the same place.

The same syntax can be used with functions that return references and with the new operator (from PHP 4.0.4):

$bar = & new fooclass();
$foo = & find_var ($bar);

But remember that NOT using the & object. If you use $ this in classes, it will operate on the current instance of the object. Assimilation without & will copy the instance (the object itself) and $ this will operate on the copy, and this procedure may not always be desirable. Usually you will need to work with a single instance, either for performance reasons or for memory consumption.

Another use would be to make changes inside objects of an ex foreach:

foreach($questions as &$question){

}

* Naturally the changes in $question will not exist in the object of array $question .

    
22.04.2015 / 02:49