为什么打印的是空行而不是5行?
function test()
{
echo "$a <br/>";
}
$a = 5;
test();
PHP中的函数不继承全局作用域或父作用域(除非使用use()
的匿名函数)。
您可以使用global
关键字访问它们
function test()
{
global $a;
echo "$a <br/>";
}
CodePad .
Jared Farish还指出全局关联数组$GLOBALS
的使用,它包含所有全局变量,并且像任何超全局变量(如$_POST
, $_GET
等)一样,无处不在。
function test()
{
echo "$GLOBALS[a] <br/>";
}
$a = 5;
test();
CodePad .
你可以使用一个匿名函数…
$a = 5;
$test = function() use ($a) {
echo $a;
};
$test();
CodePad .
作为一个脚注,尽量不要依赖全局变量。如果过度依赖它们,可能是糟糕的程序设计的标志。
你忘了使用global
function test()
{
global $a;
echo "$a <br/>";
}
$a = 5;
test();