sangkrit

Accessing Global Variables From Any Function


From one function we cannot access a variable defined in other function.

Given example defines a variable in the script but the function will not take that during execution process.

<?php

// Function will not access this variable

$num = 11;

function number () {

echo “The number is “.$num;

}

number ();

?>

When you will run this script it will give a notice in the output that, “The variable num is undefined”. And, “The number is “

As you can see that the function is not accessing the variable given in line3. The function receives the variable $num empty when it tries to access it.

This nature of PHP prevents the potential clashes in the script. In case if you want to access a variable defined in another function or elsewhere in the script then in that such cases Global Statements comes in play.

With the help of Global Statements we can access Global Variables.

For example:-

<?php

$num = 11;

function number () {

global $num;

echo “The number is “.$num;

}

number ();

?>

Accessing the script from browser gives output “The number is 11″

 


Leave a Reply