Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - convert a method to a closure

Tags:

oop

php

callback

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?

like image 455
mohammad fallah.rasoulnejad Avatar asked Jan 17 '17 15:01

mohammad fallah.rasoulnejad


2 Answers

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)

like image 72
ambienthack Avatar answered Sep 22 '22 02:09

ambienthack


PHP 8.1 update

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

like image 33
Jsowa Avatar answered Sep 22 '22 02:09

Jsowa