spajak
spajak

Reputation: 603

How to closure test in PHP

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

Answers (3)

sectus
sectus

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

salathe
salathe

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.

http://php.net/manual/en/class.closure.php

Upvotes: 3

Kris
Kris

Reputation: 41867

I usually just go with:

if ($value instanceof Closure)
{
    $value();
}

Upvotes: 0

Related Questions