[英]PHP global variable is null inside a function, but is not null outside it
[英]global inside and outside a function in PHP?
我通常会这样运行代码:
$ZANE_REGISTER_RULES='this wont print';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='this will actually print';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
但是有时(例如:如果我将其放在phpBB页面中)将无法正常工作(回声显示“ this not print”),除非我也第一次声明了全局变量:
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='my rulessssssssssssssss';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='funziona';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
我很确定第一种方法是正确的,而第二种方法则没有任何意义,但是第二种方法有效,第一种方法则无效。
请不要浪费时间回答“全局编程不好”,因为这不是手头的问题,也不是“为什么要这样做?” 因为这显然是一个例子。
发生这种情况的原因只有一个:第二个示例中的代码是在函数上下文中编译的。 这就是$ZANE_REGISTER_RULES
默认具有本地范围的原因。
如果源文件中没有包含代码本身的封闭功能,则表示该文件被函数上下文中的其他文件包含,例如:
var_access.php
echo "Hello ".$name."\n";
echo "Hello ".$_GLOBALS['name']."\n";
test_1.php
// Here var_access.php is included in the global context
$name = 'world';
include('var_access.php'); // Prints "Hello world" twice
test_2.php
// Here var_access.php is included in a function context
$name = 'world';
function func() {
$name = 'function world';
include('var_access.php'); // Prints "Hello world" and "Hello function world"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.