这个问题在这里已经有了答案:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 个回答)
5年前关闭。
为什么我不能在外部调用变量 array_filter()
,这是我的代码
class JsonSelect
{
public function jsonSource($jsonSource, $val){
$file_contents = file_get_contents($jsonSource);
if(!$file_contents){
throw new Exception('Invalid file name');
}
$json = json_decode($file_contents, true);
$q = $_POST['q'];
$filtered = $json;
if(strlen($q)) {
$filtered = array_filter($json, function ($key) use ($q) {
if (stripos($key[$val], $q) !== false) {
return true;
} else {
return false;
}
});
}
echo json_encode(array_slice(array_values($filtered), 0, 20));
}
}
这是我的图片来描述我的问题。
参数
$val
内部无法调用 $key[$val]
最佳答案
匿名函数内的变量范围仅在匿名函数内。
您需要从父作用域继承变量。
您可以在关于 anonymous functions 的 PHP 文档中找到有关它的更多详细信息。 (示例#3)
这将改变这条线:
$filtered = array_filter($json, function ($key) use ($q) {
进入这个:
$filtered = array_filter($json, function ($key) use ($q, $val) {
关于php - 不能在 array_filter() 之外调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34922801/