php如何输出一个匿名函数的代码
黄舟
黄舟 2017-04-10 14:24:09
0
4
437

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(4)
大家讲道理

用反射可以实现,当然@Rodin也说了,我简单的把代码实现了下

<?php
$test = function () {
    echo 'hello world';
};

function closure_dump($closure) {
	try {
		$func = new ReflectionFunction($closure);
	} catch (ReflectionException $e) {
		echo $e->getMessage();
		return;
	}

	$start = $func->getStartLine() - 1;

	$end =  $func->getEndLine() - 1;

	$filename = $func->getFileName();

	echo implode("", array_slice(file($filename),$start, $end - $start + 1));
}

closure_dump($test);
大家讲道理

匿名函数只在PHP 5.3.0 及以上版本有效。
说实话,之前我还没用过。

var_dump 不可以么?

Ty80

不能,要调用匿名函数,可以用$_GLOBALS[];
$GLOBALS['test']=function () {
echo'hello,world';
};
$test();
这样就可以调用了

刘奇

不能。PHP里没有可以反射自身代码的接口。

但可以通过ReflectionFunction类反射出一个方法定义所在文件起至行数,由此结合文件API读出函数的代码。

详情参见:

http://cn2.php.net/manual/en/class.re...

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板