bre*_*ett 69 php scope function
我外面有一个阵列:
$myArr = array();
Run Code Online (Sandbox Code Playgroud)
我想让我的函数访问它外面的数组,以便它可以为它添加值
function someFuntion(){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Run Code Online (Sandbox Code Playgroud)
如何为函数提供正确的范围?
Pas*_*TIN 119
默认情况下,当您在函数内部时,您无权访问外部变量.
如果希望函数有权访问外部变量,则必须global
在函数内声明它:
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅可变范围.
但请注意,使用全局变量不是一个好习惯:有了这个,你的函数就不再是独立的了.
更好的想法是让你的函数返回结果:
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;
}
Run Code Online (Sandbox Code Playgroud)
并调用这样的函数:
$result = someFunction();
Run Code Online (Sandbox Code Playgroud)
您的函数也可以获取参数,甚至可以处理通过引用传递的参数:
function someFuntion(array & $myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal; // Put that $myVal into the array
}
Run Code Online (Sandbox Code Playgroud)
然后,像这样调用函数:
$myArr = array( ... );
someFunction($myArr); // The function will receive $myArr, and modify it
Run Code Online (Sandbox Code Playgroud)
有了这个 :
有关更多信息,请阅读PHP手册的" 函数"部分,尤其是以下小节:
Max*_*s.c 21
$foo = 42;
$bar = function($x = 0) use ($foo){
return $x + $foo;
};
var_dump($bar(10)); // int(52)
Run Code Online (Sandbox Code Playgroud)
Tyl*_*ter 10
Global $myArr;
$myArr = array();
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Run Code Online (Sandbox Code Playgroud)
需要预先警告,一般人们会避开全局,因为它有一些缺点.
你可以试试这个
function someFuntion($myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
Run Code Online (Sandbox Code Playgroud)
这样就可以让你不依赖于Globals.
$myArr = array();
function someFuntion(array $myArr) {
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
Run Code Online (Sandbox Code Playgroud)