php-将方法转换为闭包 [英] php - convert a method to a closure

查看:231
本文介绍了php-将方法转换为闭包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道有什么方法可以将方法转换为php中的闭包类型吗?

I want to know is there any way to convert a method to a closure type in php?

class myClass{

 public function myMethod($param){
  echo $param;
 }

 public function myOtherMethod(Closure $param){
   // do somthing here ...
 }
}

$obj = new myClass();
$obj->myOtherMethod( (closure) '$obj->myMethod' );

这仅是示例,但我不能使用Callable然后使用[$obj,'myMethod'] 我的课很复杂,我不能只为闭包类型做任何更改. 所以我需要将方法转换为闭包. 还有其他方法还是我应该使用此方法?

this is just for example but i cant use callable and then use [$obj,'myMethod'] my class is very complicated and i cant change anything just for a closure type. so i need to convert a method to a closure. is there any other way or i should use this?

$obj->myOtherMethod( function($msg) use($obj){ 
   $obj->myMethod($msg);
} );

我希望使用较少的内存和资源消耗方式.有这样的解决方案吗?

i wish to use a less memory and resource consumer way. is there such a solution?

推荐答案

从PHP 7.1开始,您可以

Since PHP 7.1 you can

$closure = Closure::fromCallable ( [$obj, 'myMethod'] )

从PHP 5.4开始,您就可以

Since PHP 5.4 you can

$method = new ReflectionMethod($obj, 'myMethod'); $closure = $method->getClosure($obj);

$method = new ReflectionMethod($obj, 'myMethod'); $closure = $method->getClosure($obj);

但是在您的示例中,myMethod()接受一个参数,因此应像这样$closure($msg)那样调用此闭包.

But in your example myMethod() accepts an argument, so this closure should be called like this $closure($msg).

这篇关于php-将方法转换为闭包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆