假设我有一个这样的匿名 PHP 函数:
<?php
$l = function() { echo "hello world"; };
是否可以获得匿名函数$l
的字符串表示,即包含函数体的字符串?
我尝试了一些事情:
echo $l;
PHP Catchable fatal error: Object of class Closure could not be converted to stringvar_dump($l);
class Closure#1 (0) { }echo $l->__toString();
: 调用未定义的方法 Closure::__toString()get_class_methods($l)
返回array('bind', 'bindTo')
,因此似乎不存在未记录的方法$r = new ReflectionClass($l);
: getProperties(), getConstants() 和 getStaticProperties() 都是空的,还有$r->__toString()
不返回任何有用的信息。
我的代码中并不真的需要这个,我只是认为如果出现问题,它可能对日志记录有用。在我自己无法想出解决方案之后,我很好奇这是否可能。
最佳答案
您唯一的“真实”选择是使用实际的 PHP parser解析匿名函数。
不要掉进the same trap as @argon did认为一个简单的基于 substr_count
的脚本实际上可以解析 PHP 代码。它太脆弱了,即使是最简单的例子也会以光荣的方式收支平衡。
以防万一:
$dog2 = ['bark'=>function($foo = '{'){}];
Fatal error: Uncaught Exception: Too complex context definition in
关于php - 获取匿名函数的字符串表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22308365/