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?
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)
.