默认情况下,当您在函数内部时,您无权访问外部变量。
如果您希望函数可以访问外部变量,则必须
global在函数内部将其声明为:
function someFuntion(){ global $myArr; $myVal = //some processing here to determine value of $myVal $myArr[] = $myVal;}有关更多信息,请参见
可变作用域 。
但是请注意, 使用全局变量不是一个好习惯 :通过这种方法,您的函数不再是独立的。
一个更好的主意是使您的函数 返回结果 :
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}然后,像这样调用函数:
$myArr = array( ... );someFunction($myArr); // The function will receive $myArr, and modify it
有了这个 :
- 您的函数收到了外部数组作为参数
- 并且可以对其进行修改,因为它已通过引用传递。
- 比使用全局变量更好的做法是:函数是一个单元,独立于任何外部代码。



