即使使用全局关键字,PHP全局变量也未在函数内定义

时间:2022-10-08 00:41:07

Yes I know global variables is a bad practice, but ease up on that rule for this one :P

是的我知道全局变量是一种不好的做法,但是为这个规则放宽了规则:P

My code:

include('something.php'); //where $from is declared

function myfunc() {
    global $from;
    echo "from(myfunc)=$from<br />";
    ...
}

echo "from=$from<br />";
myfunc();

The result is:

结果是:

from=2010-05-01
from(myfunc)=

What's going on? :(

这是怎么回事? :(

EDIT: If it helps, all the code above is inside a view file in CodeIgniter ( and yes, I know functions are not supposed to be inside views :P )

编辑:如果它有帮助,上面的所有代码都在CodeIgniter中的视图文件中(是​​的,我知道函数不应该在内部视图中:P)

2 个解决方案

#1


24  

I'll bet a beer you are not inside the global scope with this snippet. Are you calling this from within a function?

我用这个片段打赌你不是全球范围内的啤酒。你是在函数中调用它吗?

In that case, the $from you define in something.php is not global, while the one you reference in the function is.

在这种情况下,你在something.php中定义的$不是全局的,而你在函数中引用的是。

It will probably work if you add a global $from; inside something.php before you define $from.

如果您添加全局$ from,它可能会起作用;在定义$ from之前,在something.php里面。

Needless to say, it's not a nice practice either way, and you should follow Gordon's advice.

毋庸置疑,无论如何,这都不是一个好习惯,你应该遵循戈登的建议。

#2


14  

Do yourself a favor and use Dependency Injection.

帮自己一个忙,并使用依赖注入。

function myfunc($from) {
    return "from(myfunc)=$from<br />";
}
$from = '2010-05-01';
echo myfunc($from);

Doing so will make your code more maintainable, less coupled and more easily unit-testable because it is isolated from the global scope. Plus, when you do it people think you are cool.

这样做会使您的代码更易于维护,更少耦合,更容易进行单元测试,因为它与全局范围隔离。另外,当你这样做时,人们会觉得你很酷。

#1


24  

I'll bet a beer you are not inside the global scope with this snippet. Are you calling this from within a function?

我用这个片段打赌你不是全球范围内的啤酒。你是在函数中调用它吗?

In that case, the $from you define in something.php is not global, while the one you reference in the function is.

在这种情况下,你在something.php中定义的$不是全局的,而你在函数中引用的是。

It will probably work if you add a global $from; inside something.php before you define $from.

如果您添加全局$ from,它可能会起作用;在定义$ from之前,在something.php里面。

Needless to say, it's not a nice practice either way, and you should follow Gordon's advice.

毋庸置疑,无论如何,这都不是一个好习惯,你应该遵循戈登的建议。

#2


14  

Do yourself a favor and use Dependency Injection.

帮自己一个忙,并使用依赖注入。

function myfunc($from) {
    return "from(myfunc)=$from<br />";
}
$from = '2010-05-01';
echo myfunc($from);

Doing so will make your code more maintainable, less coupled and more easily unit-testable because it is isolated from the global scope. Plus, when you do it people think you are cool.

这样做会使您的代码更易于维护,更少耦合,更容易进行单元测试,因为它与全局范围隔离。另外,当你这样做时,人们会觉得你很酷。