Mask
Mask

Reputation: 34227

Is there a way to output the definition of a function in 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?

Upvotes: 4

Views: 3756

Answers (2)

wallyk
wallyk

Reputation: 57804

I don't know of one.See code at bottom. There is a function to list all the defined functions. There's another to get the values of all the arguments to the current function, and the number of arguments. And there's one to see if a function exists. But there doesn't seem to be one to name the current function, nor any means of listing formal parameters.

Even when a runtime error occurs, it doesn't list a call stack, nor state the function that's active:

PHP Warning:  Division by zero in t.php on line 6

Edit: For the code to identify where it is, add this:

echo "At line " .__LINE__ ." of file " . __FILE__ ."\n";

It gives the output

At line 7 of file /home/wally/t.php

Edit 2: I found this function in my code which looks to be what you want:

function traceback ($showvars)
{
        $s = "";
        foreach (debug_backtrace($showvars) as $row)
        {
                $s .= "$row[file]#$row[line]: ";
                if(isset($row['class']))
                        $s .= "$row[class]$row[type]$row[function]";
                else    $s .= "$row[function]";
                if (isset($row['args']))
                        $s .= "('" . join("', '",$row['args']) . "')";
                $s .= "<br>\n";
        }
        return $s;
}

For example, it produces:

[wally@zf ~]$ php -f t.php
/home/wally/t.php#24: traceback('1')<br>
/home/wally/t.php#29: t('1', '2', '3')<br>
/home/wally/t.php#30: x('2', '1')<br>
/home/wally/t.php#31: y('2', '1')<br>
/home/wally/t.php#33: z('1', '2')<br>

Upvotes: 0

VolkerK
VolkerK

Reputation: 96199

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]);
  }
}

Upvotes: 9

Related Questions