php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #45335 By-value assignment is ignored if that variable contains a reference
Submitted: 2008-06-23 13:00 UTC Modified: 2008-11-05 11:08 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: kosthorst at apobyte dot de Assigned:
Status: Not a bug Package: Documentation problem
PHP Version: 5.2.6 OS: Debian Etch
Private report: No CVE-ID: None
 [2008-06-23 13:00 UTC] kosthorst at apobyte dot de
Description:
------------
I assign something by-reference to a variable. If I assign the same stuff again to the same variable by-value, this assignment is ignored.

In the reproduce code, $bar first is a reference to $foo. $bar is modified via array_pop(). This modifies $foo, too.

Then, $foo is assigned to $bar by-value. Again, $bar is modified via array_pop(). And again, $foo is modified too, which should not happen, because $bar should not be a reference to $foo any more.

An

   unset($bar);

right before the second assignment fixes the issue.

Reproduce code:
---------------
$foo = array(1, 2, 3, 4, 5);
$bar =& $foo;
array_pop($bar);
var_dump($foo);
$bar = $foo;
array_pop($bar);
var_dump($foo);

Expected result:
----------------
array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}
array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}

Actual result:
--------------
array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-07-14 23:58 UTC] jani@php.net
This special case propably should have an example and explanation itself in the docs.

References in PHP are "only" aliases. Doing $a =& $b means that after that $a and $b are referring to same content [1]. If you don't unset() [2] the reference, they're still referring to same content. So doing $a = $b would be basically same as doing $b = $b..

[1] http://www.php.net/manual/en/language.references.whatdo.php
[2] http://www.php.net/manual/en/language.references.unset.php

 [2008-11-05 11:08 UTC] vrana@php.net
Documentation clearly states that the reference is broken just by unsetting one of the variables.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Sat Jul 05 17:01:34 2025 UTC