Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/65651169/php-check-if-function-callable-but-not-invokable-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...