& Together with PHP operators and functions

Asked

Viewed 452 times

13

What is the meaning of the use of & together with operators and functions in PHP because I checked in some libraries (example) and functions this use (I am aware of the use together with variables has to do with the passing of pointers)

$browser = &new SimpleBrowser();

4 answers

12


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 functioning is very similar to that of the objects in general that 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 for another variable.

In some cases it can be useful in parameters. It is a form of the code to return extra results since the normal is a function or method to return 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 function’s local parameter will change the variable used to pass it. Then it works as a return.

Note that some types this is normal. Arrays and objects are by reference. The so-called primitive types 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 may also be useful in iterations:

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

I put in the Github for future reference.

Thus changing the variable $value you are changing the object element.

Apparently the use of & new is a legacy of version 4 and should no longer be used. In fact it makes no sense to use it because the new creates a reference. I won’t even look for better explanations because 4 used this, after all no one should be using it anymore. The important thing is you don’t need it anymore. I believe I was obliged by OOP no 4 was quite gambiarra and began to be part of the language in a minimally decent way in version 5.

  • But what is the meaning of the use together with the operator new?(on the link posted has the use) the same?

  • I’m trying to find out, this is very strange for me. Even p/PHP :)

  • 3

    That was used in php4 if I’m not mistaken.

  • 1

    PHP 4 Object Orientation was a pure gambiarra :\

6

This is about the Refência.

According to the PHP

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

Take 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 to say, $b points to the value of $a. It does not have an independent value, but it points to the location of memory where the value of $a was saved.

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

I will give an example of passing by reference in the functions:

$meuValor = [1, 2, 3];

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

    my_function($meuValor, 6);

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

See that the value of $meuValor was changed, without the return within the function and without the re-allocation of the function by the return of my_function.

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

The use in the Operator new was discouraged, and, if I’m not mistaken, creates an error E_STRICT while trying to make.

This occurred in versions prior to PHP 5.

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

6

The operator & has some functions currently is used as reference operator as the two replies explains well and is also using in anonymous functions.

The link example is quite peculiar it is php4 heritage where the support(adapting) to object orientation began a number of things had no implications such as all class members being public and the & =. The examples were taken from old manual session Classes and Objects(PHP 4) > References Inside the constructor

Example, runs on 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 tries to demonstrate the use new which only returns a copy of the object and its variables and the & = which returns the reference, which in kids means that some assignments may not 'sync' the values of the variables/class members/gambiarra as 'expected'.

Example 1

Here 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 because the value has been copied, while $bar2 are the same thing 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 */
?> 
  • Thank you for clarifying, I had never seen in current manuals this use.

  • Just downloading the old manual :P takes a look hehe. @Ricardo

1

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

Soon $a and $b are equal 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 (starting with PHP 4.0.4):

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

However it is worth remembering that the operator NO & will cause the copy of 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, which may not always be desirable. Normally you will need to work with a single instance, either for performance or memory consumption reasons.

Another use would be to make changes within objects of a foreach ex:

foreach($questions as &$question){

}

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.