Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable reference puzzle

Tags:

php

reference

run following code:

<?php
$a = array('yes');
$a[] = $a;
var_dump($a);

out put:

array(2) {
  [0]=>
  string(3) "yes"
  [1]=>
  array(1) {
    [0]=>
    string(3) "yes"
  }
}

run following code:

<?php
$a = array('no');
$b = &$a;
$a[] = $b;
$a = array('yes');
$a[] = $a;
var_dump($a);

out put:

array(2) {
  [0]=>
  string(3) "yes"
  [1]=>
  array(2) {
    [0]=>
    string(3) "yes"
    [1]=>
    *RECURSION*
  }
}

I have reassigned value of $a, why there are RECURSION circular references?

like image 317
Nolan Hyde Avatar asked Nov 12 '14 07:11

Nolan Hyde


People also ask

How do I reference a variable in PHP?

Pass by reference: When variables are passed by reference, use & (ampersand) symbol need to be added before variable argument. For example: function( &$x ). Scope of both global and function variable becomes global as both variables are defined by same reference.

What does &$ mean in PHP?

It means you pass a reference to the string into the method. All changes done to the string within the method will be reflected also outside that method in your code. See also: PHP's =& operator.

What is the use of $$ in PHP?

The $x (single dollar) is the normal variable with the name x that stores any value like string, integer, float, etc. The $$x (double dollar) is a reference variable that stores the value which can be accessed by using the $ symbol before the $x value.


1 Answers

To remove reference you need to call unset. Without unset after $a = array('yes'); $a still bounds with $b and they are still references. So the second part has the same behavior as first one.

Note, however, that references inside arrays are potentially dangerous. Doing a normal (not by reference) assignment with a reference on the right side does not turn the left side into a reference, but references inside arrays are preserved in these normal assignments.

http://php.net/manual/en/language.references.whatdo.php

like image 140
sectus Avatar answered Oct 09 '22 17:10

sectus