Tuesday, 21 July 2015

PHP Variable Scope

The scope of an variable is a metric about which extent the variable can be visible. There are two main categories in variable scope. These are,
  1. Local scope
  2. Global scope
php_variable_scope

Local Scope:

If the variable is recognized with in particular block structure of the program, then it is called as local variable. For example, if the variable declared inside a function will come under the local scope of that function. The number of arguments passed while calling the function, can also be recognized with in the function.

Global scope:

If variables can be recognized throughout the program, then they are in global scope. Variables in global scope can be used inside functions by using PHP global array variable or by using global keyword.

PHP variable scope example:

<?php
$count = 0;
function calculate_count() {
$count = 5;

//will print 5; the value of local variable
echo ++$count; 

// will print 0; the value of global variable declared outside function
echo $GLOBALS["count"]; 
}
calculate_count();
echo $count;
?>
There is an alternative way to access the global variable inside function discuss above. That is, the use of global keyword for variable declaration will help us in this regard. For that, we need to replace below lines,
global $count;
echo $count;
instead of,
echo $GLOBALS["count"];

0 comments:

Post a Comment