全局变量会干扰 PHP 中所需的文件吗?
我需要编辑在函数外部定义的变量(数组),这样我就可以在另一个函数中进一步使用它。我能想到的最简单的方法是将其定义为函数内部的全局变量,但我有很多需要也涉及到的文件。
全局变量的文档说它可以在“程序中的任何地方”使用。这是否意味着遍及所有文件(在所有文件的意义上是全局的)还是只是它所在的文件(本地全局的,如果有意义的话)。
我确实在这个网站上发现了一个关于全局变量的问题,建议通过引用传递它,但我在其他文件中广泛实现了这个函数,并且要求它们在调用中具有额外的变量,至少可以说是令人讨厌的。
I need to edit a variable (array) that is defined outside of the function, so I can use it in another function further in. The easiest way I can think of is to define it as global inside the function, but I have many required files involved as well.
The documentation of global variables says that it can be used "anywhere in the program." Does that imply throughout all files (is it global in a sense of across all files) or is it just the file it's in (locally global, if that makes sense).
I did find a question about globals on this site that suggests passing it by reference, but I have this function implemented extensively in other files and requiring them to have an additional variable in their calls would be obnoxious to say the least.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您在函数中定义全局变量,则您将引用全局范围的变量,并且在函数中对该变量所做的更改将对使用该全局变量的其他函数可见,无论它们位于什么文件中,只要因为包含/执行顺序是正确的。
If you define your variable global within the function, you will be referring to the globally scoped variable, and changes to that variable made within your function will be visible to other functions that use that global variable, whatever files they're in, so long as the inclusion / execution order is correct.
如果您声明全局的文件位于内存中,则该变量可供您使用。但是,如果您没有
include
或require
在某个页面上声明全局的文件,那么您将无法使用该文件。顺序也很重要。如果您尝试在设置全局变量的文件的
include
或require
之前调用该全局变量,它将不可用。If the file you declare the global in is in memory, then that variable is available for you to use. But, if you don't
include
orrequire
the file the global is declared in on a certain page, it will not be available to you.Order is also important. If you try to call the global variable before the
include
orrequire
of the file you set it in, it will be unavailable.全局变量在所有文件之间共享。顺便说一下,您应该使用
$GLOBALS['variable']
来明确您正在访问全局变量,而不是使用global $variable;
来声明它们。Globals are shared among all files. By the way, instead of declaring them with
global $variable;
, you should use$GLOBALS['variable']
to make explicit that you're accessing a global variable.如果分组在一个文件中的许多函数需要访问某些公共状态,那么您很可能需要将它们变成一个类。这几乎就是类的定义。
或者,您可以将数组转换为类,并让函数调用其方法。
也许是一个 singleton 或 注册表 (2) 可能会有所帮助。
请注意,大多数 OOP 实现都会将对象的引用作为方法的第一个参数传递,隐藏(C++、PHP)或不隐藏(C、Python)。
If a lot of functions grouped in a file require access to some common state, chances are you need to turn them into a class. That's pretty much the definition of a class.
Or you could turn the array into a class and have functions call methods on it.
Perhaps a singleton or a registry (2) could help.
Note that most OOP implementations pass a reference to the object as a method's first parameter, hidden (C++, PHP) or not (C, Python).