PHP Array Reference Confusion

With this code:

$a[1]=1;
$a[2]=& $a[1];

$b=$a;
$b[2]=7;

print_r($a);

I expected the output to be 1because it is $anot assigned by reference $b( $a = & $b), but it looks like 7. Why?

+3
source share
3 answers

How links work. What you say when you do $a[2]=& $a[1];is that both elements of $ a now have the same variable. When you do $ b = $ a, $ b and $ a are different variables, but all 4 elements inside them point to the same variable! Try to make it $b[3] = 7and see that it is not copied to $ a, because $ b and $ a are different, but $ b [2] and $ a [2] are not!

, . , .

+3

, . .

php > var_dump($a);
array(2) {
  [1]=>
  &int(1)
  [2]=>
  &int(1)
}
php > $b=$a;
php > var_dump($b);
array(2) {
  [1]=>
  &int(1)
  [2]=>
  &int(1)
}

:

php > $c[1] = 1;
php > $c[2] =& $c[1];
php > var_dump($c);
array(2) {         
  [1]=>            
  &int(1)
  [2]=>
  &int(1)
}
php > $d =& $c;
php > var_dump($d);
array(2) {
  [1]=>
  &int(1)
  [2]=>
  &int(1)
}
php > $d = array(3,4,5);
php > var_dump($c);
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}
php > var_dump($d);
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(4)
  [2]=>
  int(5)
}

, ( ) , $d $c. $b $a.

+4

, :

http://www.php.net/manual/en/features.gc.refcounting-basics.php

http://books.google.com/books?id=e7D-mITABmEC&pg=PT171&lpg=PT171&dq=php+object+zval&source=bl&ots=oawmzMtsXt&sig=mMSuVKsk6L3JWuEikJN8j7dQfRs&hl=ru&ei=JmDWTOraI4TNswaDt-jkCA&sa=X&oi=book_result&ct=result&resnum=10&ved=0CEcQ6AEwCQ#v=onepage&q=php%20object%20zval&f=false

xdebug

, "" :

class c{
    private $a = 42;
    function &a(){
        return $this->a;
    }
    function print_a () {
        echo $ this-> a;
    }
}
$ c = new c;
$ d = & $ c-> a ();
echo $ d;
$ d = 2;
$ c-> print_a ();

or pass a link to functions if you have not declared it:

function f1 (& $ s) {
    $ s ++;
}
function f2 ($ s) {
    $ s--;
}
$ s1 = 1;
$ s2 = 3;
f1 ($ s1);
f2 (& $ s2);
echo $ s1. $ s2;

also foreach can use pass-by-reference

$ a = array (1,2,3); foreach ($ a as $ key => & $ value) {$ value = 1; } $ value = 2;

0
source

Source: https://habr.com/ru/post/1773467/


All Articles