Pavel Hanpari
Pavel Hanpari

Reputation: 4714

Bind closure to class method

I have functional and python background and now I am trying PHP. I want to make something like this:

    <?php

class Test
{

    function __construct($func)
    {
        $this->build = $func;
    }


}

$test = new Test(function(){echo "neco";});
$test->build();

//my result
//Fatal error: Call to undefined method Test::build() in C:\Install\web\php\test.php on line 15


?>

But as you can see I am receiving error. Is there way to achieve class with method which depends on argument as closure in php?

Upvotes: 2

Views: 111

Answers (2)

Cristik
Cristik

Reputation: 32789

You can achieve this by implementing the magic function __call() in your Test class.

__call() is triggered when invoking inaccessible methods in an object context.

public function __call($name, $arguments) {
    if($name === 'build') {
      $this->build();
    }
}

or, with _call(), and dynamic dispatch:

public function __call($name, $arguments) {
    call_user_func_array($this->{$name}, $arguments);
}

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

Yes you can do this with __invoke(), just use it like this:

$test->build->__invoke();

output:

neco

Upvotes: 1

Related Questions