Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to output the definition of a function in PHP?

Tags:

php

function func() {
    // ...
}

I have the function name "func", but not its definition.

In JavaScript, I'd just use alert() to see the definition.

Is there a similar function in PHP?

like image 651
Mask Avatar asked Mar 01 '23 00:03

Mask


1 Answers

You can use the methods getFileName(), getStartLine(), getEndLine() defined in ReflectionFunctionAbstract to read the source code of functions/methods from their source file (if there is any).

e.g. (without error handling)

<?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]);
  }
}
like image 55
VolkerK Avatar answered Mar 16 '23 18:03

VolkerK