Alex
Alex

Reputation: 68074

Function name must be a string

I get this error when I try to call $func('something'):

if(($object instanceof MyObject) && (method_exists($object, 'foo'))){
  $func = array(&$object, 'foo');

}else{
  $func = 'fallback_foo';
}

...

echo $func('something');

What's wrong with my code?

Obviously I cannot make $func a string because it's a method specific to a object... but an array with the method name and object should work right?

Upvotes: 2

Views: 540

Answers (1)

user142162
user142162

Reputation:

Use call_user_func() or call_user_func_array(). Both support regular functions and method calls:

echo call_user_func($func, 'something');
echo call_user_func_array($func, array('something'));

Upvotes: 3

Related Questions