|
|
|---|
Scope of a VariableBy default, most variables in PHP will have only single scope. This single scope is available to the included files as well. For example
<?phpIn the above example, the variables $a, $b, $c will be available within the included file cal.php as well. But this differs for the variables used inside a function. Let's see this example:
<?php Upon execution of the above code, you will see 'Undefined Variable' notices. This is because, when you use $a, $b and $c variables within the function, they are treated as local variables and hence the value of which is not obtained from the variables used outside of the function. To be able to use these variables, you will have to declare them as global variables inside the function using the global keyword. See the modified example:
<?php Now execute the code and you will see an output. This is because after declaring the variables as global, the variables which are declared outside the function becomes available within the function as well. Note that in our example, the variable $d is still a local variable within the function print_sum(). We hope that the above explanation was clear. If not, please do contact us and give your valuable feedback. |
|
|
|---|