1

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.

3
  • 1
    use __call - 3v4l.org/oBR0L Commented Nov 26, 2022 at 17:54
  • @LawrenceCherone do you have an example of how I can use __call()? Commented Nov 26, 2022 at 18:14
  • 1
    visit the 3v4l link Commented Nov 26, 2022 at 18:34

1 Answer 1

1

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"

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.