为什么$args
是已定义在回调之外的未定义变量?我该如何解决这个问题?
我收到错误Undefined variable: args in ...
网址查询:products/category/1
$query = explode("/", $_SERVER['QUERY_STRING']);
$controller = (sizeof($query) >= 1 && !empty($query[0])) ? $query[0] : null;
$method = sizeof($query) >= 2 ? $query[1] : null;
$args = sizeof($query) >= 3 ? array_slice($query, 2, sizeof($query)) : null;
if(is_null($controller)) {
header("Location: ".URL . "?products/all");
}
if($controller === "products") {
$gw = new ProductDataGateway();
$products = null;
if($method === "all")
$products = $gw->getAllProducts();
elseif($method === "category" && sizeof($args) >= 1) {
$products = array_filter($gw->getAllProducts(), function($var) {
return $args[0] == $var['category'];
});
}
...
}
答案 0 :(得分:5)
它未定义,因为它不属于回调范围。
将use
添加到您的函数中:
$products = array_filter($gw->getAllProducts(), function($var) use ($args){
return $args[0] == $var['category'];
});