- The scope of a variable determines it’s accessibility in the program to refer it.
- PHP has four different variable scopes:
- Local
- Global
- Static
- Parameter
Local Scope
- A variable declared within a PHP function is local and can only be accessed within that function.
- For example:
<?php
$amt = 5000 ; // global scope
function my_function()
{
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.
Global Scope
- 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:
<?php
$x = 5;
$y = 10;
function sum()
{
global $x $y;
$z = $x + $y;
echo $z;
}
sum();
?>
- 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:
<?php
$x = 5;
$y = 10;
function sum()
{
$z = $GLOBALS['x'] = $GLOBALS['y'];
echo $z;
}
sum();
?>
Static Scope
- 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.
Parameters
- 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.