简体   繁体   中英

php - convert a method to a closure

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

PHP 8.1 update

PHP 8.1 introduces shorter way to create closures from functions and methods

$fn = Closure::fromCallable('strlen');
$fn = strlen(...); // PHP 8.1
 
$fn = Closure::fromCallable([$this, 'method']);
$fn = $this->method(...); // PHP 8.1
 
$fn = Closure::fromCallable([Foo::class, 'method']);
$fn = Foo::method(...); // PHP 8.1

RFC: https://wiki.php.net/rfc/first_class_callable_syntax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM