Home  >  Article  >  Backend Development  >  Can PHP Function Source Code be Retrieved Programmatically?

Can PHP Function Source Code be Retrieved Programmatically?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 07:33:30383browse

Can PHP Function Source Code be Retrieved Programmatically?

Extracting PHP Function Source Code 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn