Reputation: 603
What's the correct way to find if an object is anonymous function?
if (is_object($value) and method_exists($value, '__invoke'))
$value();
1000000 iterations, time: 3.27 s, or
if (is_object($value) and $value instanceof Closure)
$value();
1000000 iterations, time: 1,71 s
Upvotes: 0
Views: 311
Reputation: 15464
Your examples are not equal. Object that has __invoke magic method may not be Closure. So if you want only Closures check Closures. If you want all callables check callables.
You can use Callable type hint or use is_callable function.
Upvotes: 0
Reputation: 51950
The presence of an __invoke()
method does not mean that the item is an anonymous function. Any class can implement that method and an instance will be invokable.
Assuming that by "anonymous function" you mean one created with the function declaration syntax without a name (docs) – not the old create_function()
– the manual (the font of all knowledge) states (emphasis mine):
Anonymous functions, implemented in PHP 5.3, yield objects of this [Closure] type. This fact used to be considered an implementation detail, but it can now be relied upon.
Upvotes: 3
Reputation: 41867
I usually just go with:
if ($value instanceof Closure)
{
$value();
}
Upvotes: 0