Home  >  Q&A  >  body text

php如何输出一个匿名函数的代码

黄舟黄舟2749 days ago404

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-04-10 14:26:09

    用反射可以实现,当然@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);

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-10 14:26:09

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

    var_dump 不可以么?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-10 14:26:09

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

    reply
    0
  • 怪我咯

    怪我咯2017-04-10 14:26:09

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

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

    详情参见:

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

    reply
    0
  • Cancelreply