0

I know $a =& $b assigns $a as a reference to $b and I already read some answers about it, but no one provides a real useful example usage includes: What do the "=&" and "&=" operators in PHP mean?

Could any one provide a minimal example to show how =& could be useful in PHP? Why might somebody want to have two names for a single variable?

Community
  • 1
  • 1
Handsome Nerd
  • 17,114
  • 22
  • 95
  • 173
  • This question does not have an answer there! – Handsome Nerd Oct 11 '13 at 02:27
  • i thought Zenexer answer was very thorough –  Oct 11 '13 at 02:30
  • And what specifically would qualify a "real" example? The manual already contains some in the comments: http://php.net/manual/en/language.references.whatdo.php - I don't see how this broad inquiry solves a coding need. Don't forcibly try to use fringe features. – mario Oct 11 '13 at 02:35

3 Answers3

0

Here's a very simple example. You are assigning the reference of $var1 to $var2 , so when you change $var2 , $var1 value changes.

<?php
$var1 = 10;
$var2 = 20;
$var2 = &$var1;
$var2 = 200;
echo $var1; // 200;
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

Suppose some user defined function manipulate a string:

function test($string){
    $string.='bar';
    return $string;
}

In this case, you would have to attribute the return of the function back to the variable:

$foo='foo';
$foo=test($foo);

Passing the variable by reference you could eliminate some code:

function test(&$string){
    $string.='bar';
}

$foo='foo';
test($foo);

Just like, for example, the native settype works. Look the ampersand at the manual.

Rafael Barros
  • 1,043
  • 18
  • 25
0

Really useful example is modifying tree-alike structures:

Assuming you have a tree path like 'a.b.c' and an array:

array(
    'a' => array(
        'b' => array(
            'c' => array(),
        ),
    ),
)

and you need to insert a new value in the deepest element. That you could end up with something like (not tested, just for demonstration purposes):

$parts = explode('.', $path);
$node = &$tree;
foreach ($parts as $part) {
    if (isset($node[$part])) {
        $node = &$node[$part];
    } else {
        $node = null;
        break;
    }
}

if (!is_null($node)) {
    $node[] = 'new value';
}
zerkms
  • 249,484
  • 69
  • 436
  • 539