Is it possible to obtain the code from an anonymous function in PHP?
Suppose I have an anonymous开发者_JAVA技巧 function:
$func = function() { return true; }
I want to (dynamically) obtain the string "return true;"
from the variable $func
.
You can reflect such function:
$test = function() { return true; };
$r = new ReflectionFunction($test);
var_dump($r->getName());
However from what I can see in manual, PHP's reflection API doesn't provide any method that would return function's source. You can obtain start and end line of function declaration, what combined with such code-style:
$test = function() {
return false;
}
Will let you quite easily obtain function's source. But remember that this is very tricky and as @Col. Shrapnel and @DampeS8N mentioned: you really don't want to do that.
No you can't. The code is parsed and no string representation exists.
精彩评论