有没有办法在PHP中输出函数的定义?

Mas*_*ask 4 php

function func() {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我有函数名称"func",但不是它的定义.

在JavaScript中,我只是alert()用来查看定义.

PHP中是否有类似的功能?

Vol*_*erK 9

您可以使用ReflectionFunctionAbstract中定义的getFileName(),getStartLine(),getEndLine()方法从源文件中读取函数/方法的源代码(如果有的话).

例如(没有错误处理)

<?php
printFunction(array('Foo','bar'));
printFunction('bar');


class Foo {
  public function bar() {
    echo '...';
  }
}

function bar($x, $y, $z) {
  //
  //
  //
  echo 'hallo';

  //
  //
  //
}
//


function printFunction($func) {
  if ( is_array($func) ) {
    $rf = is_object($func[0]) ? new ReflectionObject($func[0]) : new ReflectionClass($func[0]);
    $rf = $rf->getMethod($func[1]);
  }
  else {
    $rf = new ReflectionFunction($func);
  }
  printf("%s %d-%d\n", $rf->getFileName(), $rf->getStartLine(), $rf->getEndLine());
  $c = file($rf->getFileName());
  for ($i=$rf->getStartLine(); $i<=$rf->getEndLine(); $i++) {
    printf('%04d %s', $i, $c[$i-1]);
  }
}
Run Code Online (Sandbox Code Playgroud)