让我的函数访问外部变量
我在外面有一个数组:
$myArr = array();
我想让我的函数访问它外面的数组,以便它可以向其中添加值
function someFuntion(){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
如何为函数提供正确的变量作用域?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
默认情况下,当您位于函数内部时,您无权访问外部变量。
如果您希望函数能够访问外部变量,则必须在函数内部将其声明为全局变量:
有关详细信息,请参阅变量范围。
但请注意,使用全局变量不是一个好的做法:这样,你的函数就不再是独立的了。
更好的主意是让你的函数返回结果:
并像这样调用该函数:
您的函数还可以接受参数,甚至处理通过引用传递的参数:
然后,像这样调用该函数:
这样:
有关详细信息,您应该阅读函数< PHP 手册的 /a> 部分,特别是以下子部分:
By default, when you are inside a function, you do not have access to the outer variables.
If you want your function to have access to an outer variable, you have to declare it as
global
, inside the function :For more informations, see Variable scope.
But note that using global variables is not a good practice : with this, your function is not independant anymore.
A better idea would be to make your function return the result :
And call the function like this :
Your function could also take parameters, and even work on a parameter passed by reference :
Then, call the function like this :
With this :
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
您可以使用匿名函数:
或者您可以使用箭头函数:
You can use an anonymous function:
Or you can use an arrow function:
预先警告一下,通常人们会远离全局变量,因为它有一些缺点。
你可以尝试这个
,这样你就不用依赖全局变量了。
Be forewarned, generally people stick away from globals as it has some downsides.
You could try this
That would make it so you aren't relying on Globals.
实现目标的一种可能不太好的方法是使用全局变量。
您可以通过将
global $myArr;
添加到函数的开头来实现这一点。但请注意,在大多数情况下使用全局变量是一个坏主意,并且可能是可以避免的。
更好的方法是将数组作为参数传递给函数:
The one and probably not so good way of achieving your goal would using global variables.
You could achieve that by adding
global $myArr;
to the beginning of your function.However note that using global variables is in most cases a bad idea and probably avoidable.
The much better way would be passing your array as an argument to your function:
这确实是关于事物的正确顺序。
It really is about the correct order of things.