PHP Local Variable
PHP Local Variables :
- A Variable which is declared inside the function or any block is called as local variable.
- Local Variable has access or life only within that function.
- Local Variable cannot be accessed from outside.
Consider the following Example -
PHP Local Variable Example :
<!DOCTYPE html> <html> <body> <?php $num = 4; function printMsg() { $num = 0; echo "\$num inside function : $num"; echo "<br />"; } printMsg(); echo "\$num outside function : $num"; ?> </body> </html>
Output :
$num inside function : 0 $num outside function : 4
Explanation :
In the above example we have just declared one variable outside the function and another variable inside the function.
function printMsg() { $num = 0; echo "\$num inside function : $num"; echo "<br />"; }
When the method gets called then variable having the local value will be printed instead of the global value. so inside the function local value 0 gets printed.
echo "\$num outside function : $num";
When control is outside the function then outer value i.e 4 will be printed.