使用array_filter处理GET请求时变量作用域问题求助
解决array_filter回调中外部变量无法访问的问题
这个问题的核心是PHP闭包函数的作用域限制——默认情况下,回调函数(闭包)无法直接访问外部作用域的变量,必须显式声明要捕获的变量。
你的代码问题所在
你定义的$weight变量在array_filter的外部,但回调函数里没有引入这个变量,所以PHP会认为它未定义。而如果在回调里直接用$args,同样因为$args不在回调的作用域内,也会报错。
修复方案
在闭包函数的参数列表后面,用use关键字把需要访问的外部变量$weight传进去就可以了。修改后的代码如下:
$app->get('/api/v1/provider/{destination}/{weight}', function ($request, $response, $args) { $em = getEntityManager(); $destination = $em->getRepository(Transport::class)->findByDestination($args['destination']); $weight = $em->getRepository(Transport::class)->findByWeight($args['weight']); // 用use($weight)把外部变量引入闭包作用域 $provider_filter = array_filter($destination, function ($data) use ($weight) { return $data->weight == $weight; }); return $response->withJson($provider_filter); });
原理说明
PHP的闭包函数不会自动继承父作用域的变量,必须通过use关键字明确指定要捕获的变量。如果需要在闭包里修改外部变量,可以使用引用传递(比如use(&$weight)),但这里你只需要读取$weight的值,所以直接传值即可。
另外额外提一句:你现在的逻辑是先按destination查询,再按weight过滤,其实可以考虑直接在Repository里写一个同时根据destination和weight查询的方法(比如findByDestinationAndWeight),这样能减少数据库查询和内存过滤的开销,代码也更简洁。
内容的提问来源于stack exchange,提问作者Lara
相关产品推荐
相关产品推荐

