Is there a 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 something here...
}
}
$obj = new myClass();
$obj->myOtherMethod((closure) '$obj->myMethod');
This is just for an example, but I can’t use callable and then use [$obj,'myMethod']
.
My class is very complicated and I can’t change anything just for a closure type.
So I need to convert a method to a closure. Is there another way or should I use this?
$obj->myOtherMethod(function($msg) use($obj) {
$obj->myMethod($msg);
});
I wish to use a less memory and in a less resource consumption way. Is there such a solution?
Since PHP 7.1 you can use:
$closure = Closure::fromCallable([$obj, 'myMethod'])
Since PHP 5.4 you can use:
$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 introduces a 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: PHP RFC: First-class callable syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With