0

Is there a significant difference between call_user_func and using variable variables?

Take for example a class such as this:

class someClass{

    protected function action_this() { ... }
    protected function action_that() { ... }

}

Is this better or more efficient

class myClass extends someClass{

    public function doAction($action='this'){
        $method="action_{$action}";
        if(is_callable (array($this,$method)) ){
            call_user_func(array($this,$method));
        }
    }

}

than

class myClass extends someClass{

    public function doAction($action='this'){
        $method="action_{$action}";
        if(is_callable (array($this,$method)) ){
            $this->$method();
        }
    }

}

Are there conditions under which one might be preferred over the other?

2
  • 1
    If you're passing arguments to a function, which do you think would be more appropriate or easier to use? Commented Dec 26, 2014 at 23:26
  • AFAIK, call_user_func is just the older way -- it was the only way to do it before they added variable functions. Now I would use variable functions. Commented Dec 26, 2014 at 23:30

1 Answer 1

5

Your example lacks clarity.

Normally it's better to have some understandable code:

$callback = array($this, $method):

if (is_callable($callback)) {
    call_user_func($callback);
}

However depending on taste, you might prefer:

if (is_callable($callback)) {
    $callback();
}

I wouldn't favor the one over the other but take the one that works.

That being said I would strongly try to not make use of magic at such a point and I personally prefer to call explicitly defined methods by their defined name and not by variable. Just to not introduce hard to debug magic.

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.