To answer your question you must first understand what is scope of variables.
The scope of a variable is the context in which it was defined. In PHP most variables have local scope only.
Scope types in PHP:
- local: the scope of a variable is the context in which it was defined. Most PHP variables have only local scope. This local scope includes the included and required archives.
- global: declared outside any function and accessed from any
place (within functions using "global $var")
- Static: same as the local variable, but keeps its value after the function is closed.
- Parameter - Same as the local variable, but with its past values
as arguments to the function.
Example of local scope:
<?php
$a = 10; // local
echo $a;
Example of global scope:
<?php
$a = 5; // Global
function minhaFuncao() {
global $a;
echo $a; // Global
}
minhaFuncao();
Note: global variaties can be accessed inside functions by adding the left of the variable to the word global. Already outside the function just enter the variable name (ex: $var)
Example passing a local variable as a parameter to the function:
<?php
$a = 5; // local
function minhaFuncao($a) {
echo $a; // local, aqui é outra variável diferente
}
minhaFuncao($a);
Obs: on minhaFuncao($a)
I could give any name to the variable, because it only exists in the local scope of the function.
For more information and examples for the other scopes see the official documentation: http://php.net/manual/en/language.variables.scope.php