PHP include_once 在函数内部具有全局效果
我在 php 中有一个函数:
function importSomething(){
include_once('something.php');
}
如何使 include_once
具有全局效果?所有导入的内容都将包含在全局范围内吗?
I have a function in php:
function importSomething(){
include_once('something.php');
}
How do i make it sot that the include_once
has a global effect? That everything imported will be included in the global scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以像这样返回文件中的所有变量...
只要
something.php
看起来像...您可以将其分配给全局变量...
如果您想变得非常疯狂,您可以
extract()
所有这些数组成员进入范围(在你的情况下是全局的)。You can return all the variables in the file like so...
So long as
something.php
looks like...Which you could assign to a global variable...
If you wanted to get really crazy, you could
extract()
all those array members into the scope (global in your case).include()
和它的朋友们是有范围限制的。除非将调用移出函数的范围,否则您无法更改包含的内容所适用的范围。我想一种解决方法是从你的函数返回文件名,并将其结果传递给
include_once()
...它看起来不太好,你只能返回一个一次(除非您返回一个文件名数组,循环遍历它并每次调用
include_once()
),但作用域是该语言构造的一个问题。include()
and friends are scope-restricted. You can't change the scope that the included content applies to unless you move the calls out of the function's scope.I guess a workaround would be to return the filename from your function instead, and call it passing its result to
include_once()
...It doesn't look as nice, and you can only return one at a time (unless you return an array of filenames, loop through it and call
include_once()
each time), but scoping is an issue with that language construct.如果你希望普通的变量定义自动传送到全局范围,你也可以尝试:
但是,如果它真的只是一个配置数组,我也会选择更明确和可重用的
return
方法。If you want ordinary variable definitions to be teleported into the global scope automatically, you could also try:
However, it if it's really just a single configuration array, I would also opt for the more explicit and reusable
return
method.我知道这个答案对于该用户来说确实很晚,但这是我的解决方案:
在您的函数内,只需将您需要覆盖的任何变量声明为全局。
示例:
需要将 $GLOBALS['text'] 设置为“yes”:
index.php 的内容:
setup.php 的内容:解决
方案类似于马里奥的解决方案,但是,只有显式全局声明的变量才会被覆盖。
I know this answer is really late for this user, but this is my solution:
inside your function, simply declare any of the vars you need to ovewrite as global.
Example:
Need to have the $GLOBALS['text'] set to "yes":
Contents of index.php:
Contents of setup.php:
The solution is similar to mario's, however, only explicitely globally-declared vars are overwritten.
从包含文件引入的所有变量都会继承包含行的当前变量范围。不过,类和函数具有全局作用域,因此这取决于您导入的内容。
http://uk.php.net/manual/en/function.include.php
(示例之前的最后一段)
All variables brought in from an included file inherit current variable scope of the including line. Classes and functions take on global scope though so it depends what your importing.
http://uk.php.net/manual/en/function.include.php
(Final Paragraph before example)