首页 > 解决方案 > 将参数传递给 Symfony 的 $cache->get()

问题描述

恐怕我有一个初学者 PHP 问题。我正在使用 Symfony 的缓存组件。https://symfony.com/doc/current/components/cache.html

我在接收 2 个参数($url,$params)的函数内部调用缓存对象。

class MainController extends AbstractController {
    public function do($url, $params) {
        $cache = new FilesystemAdapter();
        return $cache->get('myCacheName', function (ItemInterface $c) {
            global $url;
            var_dump($url); // ---> null !!!!
        }
    }
}

我的问题是,我无法访问缓存方法调用中的函数参数。$url 和 $params 为空。当然,我可以使用 MainController 类中的公共类变量将变量向后发送,但这似乎有点笨拙。

标签: phpsymfonysymfony-cache

解决方案


在 PHP 中,默认情况下,闭包无法访问其范围之外的变量,您必须use像这样:

return $cache->get('myCacheName', function (ItemInterface $c) use ($url) {
    var_dump($url); // ---> no longer null !!!!
}

推荐阅读