php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #28352 Referencing Global Variables
Submitted: 2004-05-10 19:02 UTC Modified: 2004-07-06 01:48 UTC
Votes:3
Avg. Score:4.3 ± 0.5
Reproduced:2 of 2 (100.0%)
Same Version:1 (50.0%)
Same OS:0 (0.0%)
From: hpdl at oscommerce dot com Assigned:
Status: Not a bug Package: Session related
PHP Version: 4.3.4 OS: Linux
Private report: No CVE-ID: None
 [2004-05-10 19:02 UTC] hpdl at oscommerce dot com
Description:
------------
A global variable which references a session variable 
inside a class loses its global scope. 

Reproduce code:
---------------
<?php
session_start();

class test {
  function test() {
    global $b;

    if (!isset($_SESSION['a'])) {
      $_SESSION['a'] = 0;
    }

    $b =& $_SESSION['a'];
  }
}

$test = new test;

$b++;

echo $b;

echo '<br><br>';

echo '<a href="' . basename($_SERVER['PHP_SELF']) . ((defined('SID') && strlen(SID) > 0) ? '?' . SID : '') . '">reload</a>';
?>

Expected result:
----------------
The counter shown should be incremented on each page 
reload. 

Actual result:
--------------
The counter does not get incremented and stays at 1. 
 
Changing the following line: 
 
$b =& $_SESSION['a']; 
 
to: 
 
$GLOBALS['b'] =& $_SESSION['a']; 
 
produces the expected result. 

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-07-06 01:48 UTC] sniper@php.net
This has been explained in several bug reports. Please read the 'Session related' ones with text 'references' in them..

 [2004-07-22 06:42 UTC] phpbr at ecartz dot com
There are no relevant "Session Related" bug reports with text "references", but I did find http://bugs.php.net/bug.php?id=17959 (under "Documentation problem") which includes the cited explanation.  For some reason, the documentation on the global keyword ( http://www.php.net/manual/en/language.variables.scope.php ) does not mention that the global keyword is merely a hack to set $var &= $GLOBAL['var'] rather than a persistent mark of a variable as global.  Reading the user comments or going to http://www.php.net/manual/en/language.references.spot.php is necessary to find this out.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Nov 10 20:01:29 2024 UTC