让我的函数访问外部变量 [英] Giving my function access to outside variable
问题描述
我在外面有一个数组:
$myArr = array();
我想让我的函数访问它外部的数组,以便它可以向它添加值
I would like to give my function access to the array outside it so it can add values to it
function someFuntion(){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
如何为函数赋予变量正确的作用域?
How do I give the function the right scoping to the variable?
推荐答案
默认情况下,当您处于函数内部时,您无权访问外部变量.
By default, when you are inside a function, you do not have access to the outer variables.
如果您希望您的函数可以访问外部变量,则必须在函数内部将其声明为 global
:
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
有关详细信息,请参阅变量范围.
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.
一个更好的主意是让你的函数返回结果:
function someFuntion(){
$myArr = array(); // At first, you have an empty array
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
return $myArr;
}
并像这样调用函数:
$result = someFunction();
您的函数还可以接受参数,甚至处理通过引用传递的参数:
function someFuntion(array & $myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
}
然后,像这样调用函数:
Then, call the function like this :
$myArr = array( ... );
someFunction($myArr); // The function will receive $myArr, and modify it
有了这个:
- 您的函数接收外部数组作为参数
- 并且可以修改它,因为它是通过引用传递的.
- 这比使用全局变量更好:您的函数是一个单元,独立于任何外部代码.
有关更多信息,您应该阅读函数
For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :
这篇关于让我的函数访问外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!