如何在函数中使用另一个 PHP 包含文件中的变量?
我有这个 PHP 包含文件,其中包含我将使用的所有变量。如何在函数的另一个文件中使用所有这些变量,而不在该函数中再次将它们声明为全局变量?
I have this PHP include file that has all the variables I'll be using. How can I use all those variables in another file in a function, without declaring them again as global in that function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数无法访问外部变量,除非包含它们或将它们声明为全局变量或从全局变量中获取它们。过去我创建了一个数组和易于读取的变量。然后,我引用该数组变量,并且必须通过名称访问该变量。
A function cannot access outside variables without either including them or declaring them as global or getting them from globals. In the past I have created both an array and easy to read variables. I then reference the array variable and have to reach the variable by name.
您应该将它们作为参数传递给函数。如果有太多要做这件事,请考虑使用对象而不仅仅是函数,然后在主文件中实例化该对象的实例。或者正如 Craig 提到的,除了主要函数参数之外,还可以在选项数组中传递全局变量。
You should pass them to the function as arguments. If there are to many to do this consider using objects instead of just functions, then instantiate instances of the object in your main file. Or as Craig mentions, pass the global variables in an options array in addition to your primary function arguments.
您可以通过以下方式访问全局范围的所有变量:
为了避免始终使用 $GLOBALS,您可以自动“全局化”变量:
将其放在函数中以“导入”所有变量:
并将此帮助函数放在外部的其他位置你的职能
You can access all variables of the global scope with:
To avoid the use of the $GLOBALS all the time you can "globalize" variables automatically:
Place this in your function to "import" all variables:
And put this help function somewhere else outside your function