Question:
Is it feasible to programmatically extract the source code of a PHP function based on its name? Essentially, the objective is to retrieve the function definition (e.g., function blah($a, $b) { return $a*$b; }) dynamically.
Additionally, are there any PHP functions that can be utilized for self-descriptive code reconstruction, eliminating the need to access the source file directly? Java offers the Reflection API for this purpose, but is there a PHP equivalent?
Answer:
In PHP, the ReflectionFunction class provides the functionality needed for this task. Here's an example:
<code class="php">$func = new ReflectionFunction('myfunction'); $filename = $func->getFileName(); $start_line = $func->getStartLine() - 1; // subtract 1 to account for line numbering peculiarities $end_line = $func->getEndLine(); $length = $end_line - $start_line; $source = file($filename); $body = implode("", array_slice($source, $start_line, $length)); print_r($body);</code>
The above is the detailed content of How to Programmatically Retrieve PHP Function Source Code. For more information, please follow other related articles on the PHP Chinese website!