php - 将参数传递给 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 类中的公共类变量将变量向后发送,但这似乎有点笨拙。
解决方案
在 PHP 中,默认情况下,闭包无法访问其范围之外的变量,您必须use
像这样:
return $cache->get('myCacheName', function (ItemInterface $c) use ($url) {
var_dump($url); // ---> no longer null !!!!
}
推荐阅读
- wpf - 通过具有 ContextIdle 优先级的 Dispatcher.BeginInvoke 调用时,永远不会执行委托
- pandas - 如何使用 matplotlib 绘制以下带有三列的 pandas 数据集?
- python - 2 个连接到同一脚本中的同一 API。我需要ping两个吗?
- ssms - SQL Server Management Studio 2017 - 选项卡未重绘
- haxe - 如何从 Haxe 主函数内的命令行获取参数?
- c# - 如何让我的 ServiceInstaller 项目包含 PDB 文件?
- delphi - 如何将实体添加到我的 XML 文档的 entitycollection 中?
- r - 如何接受参数、接受用户输入和存储数据?
- angular - 如何在 Ionic 3 中使用 *ngFor 访问已解析数组的内容?
- c# - 用我应该替换 dirX 让我的子弹左右射击