php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #3082 passing by reference between globals fails outside of function
Submitted: 2000-01-02 16:03 UTC Modified: 2000-05-30 20:29 UTC
From: jmeskill at libertydistribution dot com Assigned:
Status: Closed Package: Scripting Engine problem
PHP Version: 4.0 Latest CVS (02/01/2000) OS: RedHat 6.1
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: jmeskill at libertydistribution dot com
New email:
PHP Version: OS:

 

 [2000-01-02 16:03 UTC] jmeskill at libertydistribution dot com
I am trying to pass by reference from a global variable to another global variable inside of a function.  From what I can tell it does not work... however, if I try it outside of a function it works just fine.  Is this by design?  Or am I doing something wrong?  Here is an example of what works and what doesn't.

<doesnotwork>
<?php
function test()
{
  global $current;
  global $parent;

  if (!is_array($current)) {
    print("** inside if **<br>");
    $parent[0] = array();
    $current = &$parent[0];
  } else {
    print("** inside else **<br>");
    $current[0] = array();
    $current = &$current[0];
  }
}

for ($i = 0; $i < 2; $i++) {
  test();
}

$current[0] = "me";

print("Current[0]=".$current[0]."<br>");
print("Parent[0][0][0]=".$parent[0][0][0]."<br>"); 
?>

result is
** inside if **
** inside if **
Current[0]=me
Parent[0][0][0]=
</doesnotwork>

<doeswork>
<?php
for ($i=0; $i < 2; $i++) {
  if (!is_array($current)) {
    print("** inside if **<br>");
    $parent[0] = array();
    $current = &$parent[0];
  } else {
    $current[0] = array();
    $current = &$current[0];
  }
}

$current[0] = "me";

print("Current[0]=".$current[0]."<br>");
print("Parent[0][0][0]=".$parent[0][0][0]."<br>");
?>

** inside if **
** inside else **
Current[0]=me
Parent[0][0][0]=me
</doeswork>

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2000-05-30 20:29 UTC] stas at cvs dot php dot net
Yes, this is by design. When you declare something "global" inside function, 
you just assign it to be reference to global variable. When you
reassign it to be reference to something else, old reference doesn't exist anymore.
I think you should use $GLOBALS array for what you want.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 04 09:01:34 2025 UTC