Variable Scope
Scope determines where in your script a variable can be accessed.
Syntax
global $variable;The scope of a variable is the part of the script where it can be referenced.
Local and global
- A variable declared outside a function has global scope and cannot be used inside a function by default.
- A variable declared inside a function has local scope.
To use a global variable inside a function, use the global keyword.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Keeping a function's temporary variables from leaking into the rest of the program.
- Reading a global configuration value inside a function via the global keyword.
- Preventing accidental overwrites of same-named variables in different functions.
More examples
Local scope
Variables declared inside a function are invisible outside it.
<?php
function greet() {
$msg = "Hi";
echo $msg;
}
greet();
// echo $msg; // Error: $msg only exists inside greet()The global keyword
global pulls an outer-scope variable into the function.
<?php
$appName = "SoundsCode";
function banner() {
global $appName;
echo "Welcome to $appName";
}
banner();The $GLOBALS array
$GLOBALS holds every global by name — an alternative to the global keyword.
<?php
$count = 5;
function show() {
echo $GLOBALS['count'];
}
show();
Discussion