是否可以从 PHP 中的匿名函数获取代码?
假设我有一个匿名函数:
$func = function() { return true; }
我想(动态)从变量 $func
获取字符串 "return true;"
。
Suppose I have an anonymous function:
$func = function() { return true; }
I want to (dynamically) obtain the string "return true;"
from the variable $func
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以反射这样的函数:
但是从我在手册中看到的,PHP的反射API没有提供任何返回函数源代码的方法。你可以获取函数声明的起始行和结束行,结合这样的代码风格:
会让你很容易地获取函数的源代码。但请记住,这是非常棘手的,正如@Col. Shrapnel 和 @DampeS8N 提到:你真的不想这样做。
You can reflect such function:
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:
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.