The following code produces a warning:
<?php
$GLOBALS['foo'] = "Example content<BR><BR>";
echo $foo; // that works!
Test();
function Test()
{
echo $foo; // that doesn't work!
}
?>
The warning is:
Notice: Undefined variable: foo
How come ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Inside the function,
$foois out of scope unless you call it as$GLOBALS['foo']or useglobal $foo. Defining a global with$GLOBALS, although it improves readability, does not automatically reserve the variable name for use in all scopes. You still need to explicitly call the global variable inside lower scopes to make use of it.It’s even possible to have both a local and a global
$fooin the same function (though not at all recommended):Review the PHP documentation on variable scope and the
$GLOBALSdocumentation for more examples.