1

Looking for the way to assign a function to a class variable and then call it.

I know you can assign the class var to another variable and then call it, but I am looking for a way to call without creating temporary variables and cluttering up my code.

Are temporary variables or using call_user_func() my only options?

class MyClass {
    public $callMe;
    public function __construct() {
        $this->callMe = function(...$args) {
            print_r(['HIT', $args]);
        };

        // $this->callMe('asd', 'sda');
        // Error: PHP Fatal error:  Call to undefined method test::callMe()

        // This works, but I would prefer not to create temporary variables for this
        $tmp = $this->callMe;
        $tmp('sd','adsf','fdas');
    }
}

1 Answer 1

2

Try one of the following:

($this->callMe)('sd','adsf','fdas');
call_user_func($this-callMe, 'sd','adsf','fdas');
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.