我在外面有一个数组:
$myArr = array();
我想让我的函数访问其外部的数组,以便它可以向其中添加值
function someFuntion(){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
如何为函数赋予变量正确的作用域?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以使用匿名函数:
$foo = 42; $bar = function($x = 0) use ($foo) { return $x + $foo; }; var_dump($bar(10)); // int(52)或者您可以使用箭头函数:
默认情况下,当您位于函数内部时,您无权访问外部变量。
如果您希望函数能够访问外部变量,则必须在函数内部将其声明为全局变量:
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; }并像这样调用函数:
您的函数还可以接受参数,甚至处理通过引用传递的参数:
function someFuntion(array & $myArr){ $myVal = //some processing here to determine value of $myVal $myArr[] = $myVal; // Put that $myVal into the array }然后,像这样调用该函数:
有了这个:
有关详细信息,您应该阅读函数 部分,特别是以下子部分: