Steve Clay
Steve Clay

Reputation: 8781

Can I find where a PHP anonymous function was defined?

Closures don't seem to be fully exposed to reflection. On inspection as an object, it doesn't seem to have anything useful:

$foo = function ($a, $b) {};
$ref = new ReflectionObject($foo);
var_dump($ref->getFileName()); // false

You can get parameters of the anonymous function:

$invoker = $ref->getMethod('__invoke');
var_dump($invoker->getParameters()); // "a" and "b"!

But not where it was defined:

var_dump($invoker->getFileName()); // false

Any ideas?

Upvotes: 1

Views: 699

Answers (1)

Chris Trahey
Chris Trahey

Reputation: 18290

I think what you are looking for is ReflectionFunction instead of ReflectionObject.

Here is the reference. It even includes an isClosure method, and accepts a closure as a constructor argument. :-)

Example:

$callback = function (){ echo 'hello'; };
$r = new ReflectionFunction($callback);
$startLine = $r->getStartLine();
$file = $r->getFileName();
$is_closure = $r->isClosure();

Upvotes: 3

Related Questions