php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #75184 A $GLOBAL variable is magically modified
Submitted: 2017-09-11 09:57 UTC Modified: 2017-09-11 10:08 UTC
From: hdfou at yahoo dot fr Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 7.0.23 OS: windows 10
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: hdfou at yahoo dot fr
New email:
PHP Version: OS:

 

 [2017-09-11 09:57 UTC] hdfou at yahoo dot fr
Description:
------------
A $GLOBALS value is updated and should not be updated.

Test script:
---------------
$GLOBALS['availableLanguages'] = array(
 'fr' => array( 'n' => 'Français' ) , 
 'en' => array( 'n' => 'English' ) 
);

$GLOBALS['lang']='fr';

echo 'At the biginning, $GLOBALS[\'lang\']=' . $GLOBALS['lang'] . '<br />' ;

foreach( $GLOBALS['availableLanguages'] as $lang => $value){
 echo '$lang=' . $lang . '<br />';
}

// nowhere $GLOBALS['lang'] has been changed by the script but at the end
// $GLOBALS['lang'] = "en" instead of "fr".

echo '<br />$GLOBALS[\'lang\']="' . $GLOBALS['lang'] . '" ' . ($GLOBALS['lang']=='en' ? '<b style="color:red;">THIS SHOULD BE "fr"</b>' : '<b style="color:green;">OK</b>' ) ;
exit();




Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-09-11 10:08 UTC] kelunik@php.net
-Status: Open +Status: Not a bug
 [2017-09-11 10:08 UTC] kelunik@php.net
You're in the global scope with your "foreach".

foreach( $GLOBALS['availableLanguages'] as $lang => $value){

That modifies the global $lang.

I'd recommend to not use $GLOBALS.
 [2017-09-11 10:15 UTC] spam2 at rhsoft dot net
i second not to use $GLOBALS at all, especially in code whcih runs in the global scope because it's just a useless additional OPCODE and in many cases harder for a IDE to do sane autocompletion

within function just do "global $varname" which is one OPCODE instead one for each usage and so no difference if it's used only once and faster when used multiple times

in the sample of the bugreporter $GLOBALS can be completly removed and then you see $lang is used before and within the loop and it's only not obvious because of the inconsistent usage auf $GLOBALS['lang'] and $lang which are both the same var in the same scope
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri Jul 04 09:01:34 2025 UTC