<?php
$foo = 1;
function meh(){
// <-- $foo can't be accessed
}
It doesn't look like a global variable. However, does it have disadvantages like global stuff if it's outside the function?
Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.
Inside a function or a block which is called local variables, In the definition of function parameters which is called formal parameters. Outside of all functions which is called global variables.
Variables declared outside of any function become global variables. Global variables can be accessed and modified from any function. In the above example, the variable userName becomes a global variable because it is declared outside of any function.
Global VariablesThey are declared at the top of the program outside all of the functions or blocks. Declaring global variables: Global variables are usually declared outside of all of the functions and blocks, at the top of the program. They can be accessed from any portion of the program.
All variables defined outside any function are declared in global scope. If you want to access a global variable you have two choices:
Use the global keyword
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
?>
Or use the $GLOBALS
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
?>
Read more at http://php.net/manual/en/language.variables.scope.php
Yes. They can be accessed from any location, including other scripts. They are slightly better as you have to used the global
keyword to access them from within a function, which gives more clarity as to where they are coming from and what they do.
The disadvantages of global variables apply, but this doesn't instantly make them evil as is often perceived in some OO languages. If they produce a good solution that's efficient and easily understandable, then you're fine. There are literally millions of succesful PHP projects that use global variables declared like this. The biggest mistake you can make is not using them and making your code even more complicated when it would have been perfectly fine to use them in the first place. :D
<?php
$foo = 1;
function meh(){
global $foo;
// <-- $foo now can be accessed
}
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With