Home > Net >  PHP Adding a method to a class via the constructor
PHP Adding a method to a class via the constructor

Time:11-27

how would I go about adding a method to a PHP class via its constructor to be called back at a later date?

Say I have a PHP class like this:

class Action
{
    public $callback = null;

    public function __construct(callable $callback)
    {
        $this->callback = $callback;
    }
}

And I want to be able to call that method like this:

$action = new Action(function($value) {
    // do something with $value;
});

$action->callback('abc');

However when I do the above I get this error:

Call to undefined method Action::callback()

I've tried googling for some answers however so far I haven't had much luck, any advice would be much appreciated.

CodePudding user response:

You are trying to call a function named 'callback'. You can get the property to call it:

call_user_func($action->callback, 'abc');

or

$fn = $action->callback;
$fn('abc');

Example:


class Action
{
    public $callback = null;

    public function __construct(callable $callback)
    {
        $this->callback = $callback;
    }
}
$action = new Action(function($value) {
    var_dump($value);
});

call_user_func($action->callback,12); // int(12)

$fn = $action->callback;
$fn('abc'); // string(3) "abc"

  • Related