简体   繁体   English

全局内部和外部函数在PHP中?

[英]global inside and outside a function in PHP?

I usually run code like this just fine: 我通常会这样运行代码:

$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"

But sometime (eg: if I put this inside a phpBB page) this doesn't work (the echo says "this wont print") unless I declare the variable global the first time too: 但是有时(例如:如果我将其放在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"

I'm pretty sure that the first way is the correct one and the second one just doesn't mean anything, nevertheless the second one works, the first one doesn't. 我很确定第一种方法是正确的,而第二种方法则没有任何意义,但是第二种方法有效,第一种方法则无效。

PLEASE don't waste time replying "global are bad programming" because this is not the issue at hand, neither "why would you do such a thing?" 请不要浪费时间回答“全局编程不好”,因为这不是手头的问题,也不是“为什么要这样做?” because this is obviusly an example. 因为这显然是一个例子。

There is only one reason why this might be happening: the code in the second example is being compiled in the context of a function. 发生这种情况的原因只有一个:第二个示例中的代码是在函数上下文中编译的。 That's why $ZANE_REGISTER_RULES has local scope by default. 这就是$ZANE_REGISTER_RULES默认具有本地范围的原因。

If there is no enclosing function in the source file where the code itself appears, this means that the file is being included by some other file inside a function context, for example: 如果源文件中没有包含代码本身的封闭功能,则表示该文件被函数上下文中的其他文件包含,例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM