Is there a way to infer a function definition in PHP?

function func() { // ... } 

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

In JavaScript, I just used alert() to see the definition.

Is there a similar function in PHP?

+4
source share
2 answers

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

eg. (no 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]); } } 
+8
source

I do not know one thing. See the code below. There is a function to display all defined functions . There is another to get the values โ€‹โ€‹of all the arguments of the current function , and the number of arguments . And there is one to see if the function exists . But, it seems, there is no name for the current function or any means for listing formal parameters.

Even when a run-time error occurs, it does not display the call stack and does not indicate the active function:

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

Edit: to determine the code where it is, add the following:

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

He outputs

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

Edit 2: I found this function in my code that looks the way 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> 
0
source

All Articles