Skip to content
Advertisement

PHP check if function callable but not invokable object?

I want a custom is_callable_func function which captures correctly functions and closures but disregards custom objects which implement the __invoke method.

Example:

function test1()
{
   // ..
}

class MyObject
{
  public function test2()
  {
     // ..
  }
}

class MyInvokableObject
{
   public function __invoke()
   {
      // ..
   }
}

$test3 = function() {
  // ..
};


echo is_callable_func('test1'); // true
echo is_callable_func([new MyObject(), 'test2']); // true
echo is_callable_func($test3); // true
echo is_callable_func(new MyInvokableObject()); // must return false!!

I tried using:

function is_callable_func($f)
{
   return is_callable($f) && !is_object($f);
}

but it doesnt work, since, for example, anonymous functions are objects. Possible??

PS: would appreciate if proposed solution is backwards-compatible to php 5.3

Advertisement

Answer

You can check what type of object the callable is, a closure will be an instance of Closure

function is_callable_func($f)
{
    return is_callable($f) && ( !is_object($f) || $f instanceof Closure);
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement