Home > Article > Backend Development > Can PHP Function Source Code be Retrieved Programmatically?
Question:
Is it possible to programmatically retrieve the source code of a PHP function given its name?
Background:
For example, consider the following code:
<code class="php">function blah($a, $b) { return $a*$b; } echo getFunctionCode("blah");</code>
Is it feasible to implement such a function?
Answer:
Yes, this is achievable using PHP's ReflectionFunction class. Here's a code snippet that demonstrates how:
<code class="php">$func = new ReflectionFunction('myfunction'); $filename = $func->getFileName(); $start_line = $func->getStartLine() - 1; // subtract 1 to obtain the correct function block $end_line = $func->getEndLine(); $length = $end_line - $start_line; $source = file($filename); $body = implode("", array_slice($source, $start_line, $length)); print_r($body);</code>
This code retrieves the function's source code by parsing the PHP source file and extracting the lines corresponding to the function body. The ReflectionFunction class provides convenient methods to determine the function's file location, starting and ending line numbers.
The above is the detailed content of Can PHP Function Source Code be Retrieved Programmatically?. For more information, please follow other related articles on the PHP Chinese website!