To answer your question, you first need to understand what is variable scope .
The scope of a variable is the context where it was defined. In PHP most of the variables have only local scope.
Scope types in PHP:
-
local : The scope of a variable is the context where it was defined. Most PHP variables have only local scope. This local scope includes the included and required files.
-
global : declared out of any function and accessed from any
place (within functions using "global $ var")
-
static : equals the local variable, but retains its value after the function terminates.
-
parameter - Same as local variable, but with its past values
as arguments to the function.
Local scope example:
<?php
$a = 10; // local
echo $a;
Global Scope Example:
<?php
$a = 5; // Global
function minhaFuncao() {
global $a;
echo $a; // Global
}
minhaFuncao();
Note: global variaties can be accessed within functions by adding the variable's left to the global keyword. Once outside the function just enter the name of the variable (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);
Note: In% w / w I could give any name to the variable, since it only exists in the local scope of the function.
For more information and examples for the other scopes consult the official documentation: link
p>