Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP: Why does this reference passing not work as expected?

consider the following code:

class FOO {
  public $v = [];

  function &refv1() {
     return $this->v[1];
  }
  function refv2(&$ref) {
    $ref = &$this->v[2];
  }
}
$FOO = new FOO();

//this works
$acc = &$FOO->refv1();
$acc = '5';
echo $FOO->v[1]; // 5

// this does not work
$bcc = null;
$FOO->refv2($bcc);
$bcc = '10';
echo $FOO->v[2]; // not set!

Its basically the same but in the first place I return a reference and in the second case I pass it and set it to a ref inside the function. Why doesnt this work, and how can I set a passed reference as an accessor to an array like in the first function…?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think your intention is to write this:

class FOO {
  public $v = [];

  function &refv1() {
     return $this->v[1];
  }
  function refv2(&$ref) {
    $this->v[2] = &$ref;
  }
}
$FOO = new FOO();

//this works
$acc = &$FOO->refv1();
$acc = '5';
echo $FOO->v[1]; // 5

// this does not work
$bcc = null;
$FOO->refv2($bcc);
$bcc = '10';
echo $FOO->v[2]; // 10

What went wrong with your code? Basically you got $this->v[2] and $ref the wrong way around in the refv2() method. The right side is assigned to the left side, not the other way around. In your code $this->v[2] is never assigned an value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading