php - convert a method to a closure

百般思念 提交于 2020-01-13 10:34:26

问题


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' );

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?


回答1:


Since PHP 7.1 you can

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

Since PHP 5.4 you can

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

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



来源:https://stackoverflow.com/questions/41701482/php-convert-a-method-to-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!