如何在php的回调函数中传递参数? [英] How to pass argument in callback function in php?
问题描述
我有一个Repository类,其方法如下:
I have Repository class with a method as follows:
public function GetOne($id){
$method = __METHOD__;
$post = null;
$post = $this->CacheManager($method, function($id) {
return DB::select("select * from posts where id = ?", [$id]);
});
return $post;
}
我想缓存结果,但是在闭包/回调函数中,$ id参数不起作用. CacheManager是我在存储库中使用它的一个特征.
I want to cache the result, but in the closure/callback function the $id parameter is not working. The CacheManager is a trait where I'm using it in my repository.
public function CacheManager($method, $fn) {
$obj = null;
if(!$this->HasCache($method)){
$obj = $fn();
}else {
$obj = $this->GetCache($method);
}
return $obj;
}
我还有其他一些没有参数的方法,它们正在按预期方式工作.
I have some other methods without parameters and they're working as intended.
推荐答案
使用 use
. :D
Use use
. :D
使用use
子句,可以将变量从父作用域导入到函数的作用域中.
With the use
clause, you can import variables from the parent scope into the scope of the function.
public function GetOne($id){
$method = __METHOD__;
$post = null;
$post = $this->CacheManager($method, function() use ($id) {
return DB::select("select * from posts where id = ?", [$id]);
});
return $post;
}
只是一个旁注.由于看起来您正在构建缓存机制,因此您还需要在缓存中包括该ID.当前,您仅按$method
进行检查,但是对于每个id,您可能会有一个不同的缓存条目,该缓存条目可能存在或可能不存在.因此,我认为在您的函数中,您需要执行以下操作,以使缓存键更具唯一性.我也将参数$method
称为$cacheKey
之类的东西,因为它不应该链接到方法本身的名称到缓存.
Just a side note. Since it looks you are building a caching mechanism, you will need to include the ID in the cache as well. Currently you only check by $method
, but for each id you will probably have a different cache entry which may or may not exist. So I think in your function you need to do something like the line below to make the cache key more unique. I would also call the parameter $method
something like $cacheKey
instead, since to the cache it shouldn't be linked to a method name per se.
$method = __METHOD__ . ";$id";
PHP 7.4的更新:箭头功能
用于箭头功能的RFC (又称简短关闭")已通过投票.
The RFC for arrow functions (AKA 'short closures') has passed voting.
对于这些参数,您无需指定要关闭的参数,因为它们始终只能具有一个表达式,因此,它们使用的任何表达式/值都可以(并将)取自父函数范围.
With these you don't specify the parameters you want to close in, because they can only have a single expression anyway, so any expression/value they use can (and will) be taken from the parent function scope.
由于在这种情况下,匿名函数只有一个语句,因此可以将其重写为箭头函数.然后,对缓存管理器的调用将如下所示:
Since in this case the anonymous function just has a single statement, it can be rewritten into an arrow function. The call to the cache manager will then look like this:
public function GetOne($id){
$method = __METHOD__;
$post = null;
$post = $this->CacheManager($method, fn() => DB::select("select * from posts where id = ?", [$id]));
return $post;
}
这篇关于如何在php的回调函数中传递参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!