简体   繁体   中英

Difference between $GLOBALS and uppercase $var

What is (if any) the difference between declaring variable in the $GLOBALS scope and declaring an uppercase variable?

I've look around for the answer, here some links with interesting information but I didn't find an answer to my question.

PHP global in functions
what is the difference between GLOBALS and GLOBAL?
http://php.net/manual/en/language.variables.scope.php
http://php.net/manual/en/reserved.variables.globals.php
How to declare a global variable in php?

a little test shows us:

$FOO='BAR';
$GLOBALS['foo']='bar';

function ufoo(){ echo $GLOBALS['FOO']; }
function lfoo(){ echo $GLOBALS['foo']; }

ufoo(); //outputs BAR
lfoo(); //outputs bar

About using constants: there are some limitations as described here, so they will not work for me. http://php.net/manual/en/language.constants.php Also, a Constant defined as object or array will take up disk space by adding lines to my error log:

class foo_bar{
  var $a;
  var $b;
}
$foo_bar_object=new foo_bar();
$foo_bar_object->a='foo';
$foo_bar_object->b='bar';
define('FOO_BAR_OBJECT',$foo_bar_object);

$foo_bar_array=array('foo','bar');
define('FOO_BAR_ARRAY',$foo_bar_array);

print_r(FOO_BAR_ARRAY);
print_r(FOO_BAR_OBJECT);

PHP Warning: Constants may only evaluate to scalar values
PHP Warning: Constants may only evaluate to scalar values
PHP Notice: Use of undefined constant FOO_BAR_ARRAY - assumed 'FOO_BAR_ARRAY'
PHP Notice: Use of undefined constant FOO_BAR_OBJECT - assumed 'FOO_BAR_OBJECT'


Please cut down the thread about bad practice when it comes to use $GLOBALS. It's in php and it can be useful when used in a proper way. Just like anything, it's not because some people's abuse of something that everyone should avoid it.

Defining a variable in the global scope is the same as defining it as a property of the $GLOBALS superglobal array. It works both ways regardless of case of the variables.

<?php
$test1 = "Hello World";
echo $GLOBALS["test1"];
echo "\n";
$GLOBALS["test2"] = "Goodbye World";
echo $test2;

// outputs
// Hello World
// Goodbye World     

Example

As for exposing an array or object globally (which is pretty much universally considered bad practice) you have several options. As you have stated define and const only work with scalar values but you can access the object through any of the PHP superglobals including $GLOBALS.

Alternatively you can use the Singleton anti pattern or a static class property . All of which are accessible regardless of scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM