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?

3
  • This question does not have an answer there! Commented Oct 11, 2013 at 2:27
  • i thought Zenexer answer was very thorough Commented Oct 11, 2013 at 2:30
  • And what specifically would qualify a "real" example? The manual already contains some in the comments: 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. Commented Oct 11, 2013 at 2:35

3 Answers 3

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; 
Sign up to request clarification or add additional context in comments.

1 Comment

I am looking for a real useful example.
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.

Comments

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'; } 

2 Comments

$tree was initialized?
@Rafael Barros: of course not - the data appears from somewhere magically

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.