Discussion board
What is variable scope ?
By Arun Desai
variable scope....
Reply
Post   Reset
Teacher SiliconIndia replied to Arun Desai Wednesday, March 17, 2010
Hi Arun,
Consider the following code
<?php
$a = 4;
function sendValue($x)
{
echo $x;
}
sendValue($a);
?>
In the above code, the variable, $a is declared outside the function. The definition of the function, simply sends the value of its argument to the browser. When the function is called, the variable, $a is sent as argument. This value is echoed. Now note two things: This variable is declared outside the function. It is passed to the function as an argument. In the function definition, the variable echoed is the parameter variable of the function and not the variable declared outside the function. As the value of the variable, declared outside the function is passed as argument, in the definition of the function, this value becomes the value of the parameter variable.
When a variable is declared outside a function and passed as argument to the function, the definition of the function sees the variable. The above code works. Now, try the following code and note that it does not work
<?php
$a = 4;
function sendValue()
{
echo $a;
}
sendValue();
?>
Here, the variable is still declared outside the function. The function does not have any parameter. When the function is called, the variable is not sent as an argument. However, in the function definition, the variable declared outside, and not the parameter variable, is expected to be echoed. In some computer languages, the above code will work. In PHP, it does not work because a PHP function cannot see a variable declared outside its definition; that is just the rule of PHP.