Why is an empty line printed instead of 5?
function test()
{
echo "$a <br/>";
}
$a = 5;
test();
Why is an empty line printed instead of 5?
function test()
{
echo "$a <br/>";
}
$a = 5;
test();
Functions in PHP do not inherit global scope or parent scope (unless using an anonymous function with use()
).
You can use the global
keyword to access them.
function test()
{
global $a;
echo "$a <br/>";
}
Jared Farish also points out the use of the global associative array $GLOBALS
which holds all global variables and which, like any super global such as $_POST
, $_GET
, etc, is in scope everywhere.
function test()
{
echo "$GLOBALS[a] <br/>";
}
$a = 5;
test();
You could use an anonymous function...
$a = 5;
$test = function() use ($a) {
echo $a;
};
$test();
As a footnote, try not to rely on global variables. They can be a sign of poor program design if you overly rely on them.
you forgot to use the global
function test()
{
global $a;
echo "$a <br/>";
}
$a = 5;
test();
` isn't outputted? – Jared Farrish Oct 30 '11 at 23:26
`. I suppose I should have said it should *issue a notice*. – alex Oct 30 '11 at 23:35
` in the HTML source would be an indication of the overall problem, regardless of any (non-existent) error reporting. – Jared Farrish Oct 30 '11 at 23:36