变量分为全局变量和局部变量。学过C语言的童鞋都知道,全局变量的作用域是整个整个文件。在即使在函数内部也有效,但在php中,如果在函数中使用全局变量,php会认为这个变量没有定义。如果我们需要在函数内部使用这个全局变量,这时我们就需要在函数内部,这个全局变量前加关键字global。下面是自己写的一个小demo。用来证明我上面说的
<?php
$str = "string";
function test()
{
if (isset($str))
{
echo "the string is defined";
}
else
{
echo "the string is undefined";
}
}
test();
?>
这是在浏览器中的运行结果:
the string is undefined
<?php
$str = "string";
function test()
{
global $str;//上面的test函数中没有这句话
if (isset($str))
{
echo "the string is defined";
}
else
{
echo "the string is undefined";
}
}
test();
?>
这是在浏览器中的运行结果:
the string is defined
$GLOBALS — 引用全局作用域中可用的全部变量
一个包含了全部变量的全局组合数组。变量的名字就是数组的键。
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "\n";
echo '$foo in current scope: ' . $foo . "\n";
}
$foo = "Example content";
test();
?>
以上例程的输出类似于:
$foo in global scope: Example content
$foo in current scope: local variable