- The scope of a variable determines it’s accessibility in the program to refer it.
- PHP has four different variable scopes:
- A variable declared within a PHP function is local and can only be accessed within that function.
- For example:
$amt = 5000 ; // global scope
echo $amt ; // local scope
- The above script will not produce any output because the echo statement refers to the local scope variable $amt, which has not been assigned a value within that function.
- We can use local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared.
- The scope of local variables is limited to that functions only in which they are declared and are deleted as soon as the function is over.
- Variables that are declared outside the functions have global scope.
- Global variables can be accessible from any part of the script that is not inside a function.
- To access a global variable from within a function, use the global keyword. For example:
$x = 5;
$y = 10;
global $x $y;
$z = $x + $y;
- The above script will output 15.
- PHP also stores all global variables in $GLOBALS[index] array.
- We can access individual variable by providing name of the variable as index.
- This global array is also accessible from within functions and can be used to update global variables directly.
- The previous example can be rewritten using $GLOBALS array as follow:
$x = 5;
$y = 10;
$z = $GLOBALS['x'] = $GLOBALS['y'];
- A soon as execution of a function is completed; all of its variables are deleted.
- In some cases you want a local variable not to be deleted.
- We can use the static keyword to achieve this while declaring the variable as follow:
static $my_static_var ;
- Each time the function is called, that variable will still have the data it contained the last time the function was invoked.
- Note: The variable is still local to the function.
- A parameter is a local variable whose value is passed to the function at the time of function call.
- Parameters are also referred to as arguments.
- Parameters are declared in a parameter list as part of the function declaration as follow:
function func_name ($para1,$para2,...)
// function body
- Parameters will be discussed in more detail while dealing with functions.