One may seek a method to obtain the source code of a specific function by its name. For instance, consider a function named "blah":
<code class="php">function blah($a, $b) { return $a*$b; }</code>
Is there a programmatic approach to retrieve the code snippet of "blah"?
In PHP, the ReflectionFunction class provides the means to retrieve function metadata, including its source code. Here's how you can accomplish this:
<code class="php">$func = new ReflectionFunction('blah'); $filename = $func->getFileName(); $start_line = $func->getStartLine() - 1; // Adjust for line numbering indexing $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 accomplishes the following:
This approach allows you to retrieve source code during runtime, providing you with more flexibility in your PHP development.
The above is the detailed content of How to Programmatically Retrieve Function Source Code in PHP?. For more information, please follow other related articles on the PHP Chinese website!