为什么是$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'];
});
}
...
}
Run Code Online (Sandbox Code Playgroud)
它未定义,因为它不在回调范围内.
添加use到您的功能:
$products = array_filter($gw->getAllProducts(), function($var) use ($args){
return $args[0] == $var['category'];
});
Run Code Online (Sandbox Code Playgroud)