Global variables are NOT necessarily available for use within PHP functions, unlike their use in other languages (i.e., JavaScript). This page scopetest2.php, whose code is printed below, shows an example of what happens when a function tries to access a variable that has not been specifically made available to it. The $life variable is defined BEFORE the meaningOfLife() function. As such, it is not automatically available for use within the function itself. The same thing would happen if the variable had been defined elsewhere on the page, or within another function. This is actually an important safeguard, as the text reminds us, "because it saves you from potential clashes betwen identically named variables, and a function can always demand an argument if it needs information about the outside world." (139) To see an example of how you CAN access global variables from within a function, check out scopetest3.php.
The PHP code printed below has been removed from this page's source code because it causes errors. See the results here: scopetest2.php.
<?php
$life = 42;
function meaningOfLife() {
echo "The meaning of life is ".$life";
}
meaningOfLife();
?>