Can PHP Function Source Code be Retrieved Programmatically?

Patricia Arquette
Release: 2024-10-19 07:33:30
Original
382 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!