onlyoffice 回调传参数,如何在php的回调函数中传递参数?

本文介绍了一个关于PHP中使用闭包时遇到的问题,即如何正确传递参数到闭包内。通过使用use子句导入外部作用域的变量解决了$id参数无法在缓存管理器的闭包中正常工作的问题,并提供了兼容PHP 7.4版本的箭头函数示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

}

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 use. :D

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;

}

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";

Update for PHP 7.4: arrow functions

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值