
PHP Variable scope is the important process. PHP variable have three type of scope.Local,Global and static.See below for explanation.
Variable Scope:
- Local
- Global
- Static
Local Variable:
Local Variables can be declared inside the function. You can use the variable value only inside the function.
Global Variable:
A Global Variable can be declared outside the function you can access the variable value outside the function only.
Example:
<?php $myname =”labw3”; // Global Variable function localvar(){ $name = “labw3.com”; // Local Variable echo “Website url is $name”; } localvar(); echo “Site name is $myname”; ?>Global Keyword:
You can use the global variable value also inside the function using the Global keyword.
Example:
<?php $firnum = 10; $secnum = 10; $sum = 0; function addnum(){ global $firnum, $secnum, $sum; //global keyword $sum = $firnum + $secnum; } addnum(); echo “Answer is : $sum”; ?>
Static Keyword:
In PHP a variable declared inside the function the value of the variable will be loss after the function execution over. If you want to keep the value future use you must give the keyword static to keep value in the variable for future use. See below.
Example:
<?php function mystatic(){ static $num = 2; //static keyword echo $num; } mystatic(); ?>