Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reconstruct / get source code of a PHP function

Tags:

php

reflection

Can I programmatically get the source code of a function by its name?

Like:

function blah($a, $b) { return $a*$b; } echo getFunctionCode("blah"); 

is it possible?

Are there any php self-descriptive functions to reconstruct function/class code? (I mean instead of getting source code right from the source file.)

In Java there exists: http://java.sun.com/developer/technicalArticles/ALT/Reflection/

like image 735
Marek Sebera Avatar asked Aug 11 '11 13:08

Marek Sebera


2 Answers

Expanding on the suggestion to use the ReflectionFunction, you could use something like this:

$func = new ReflectionFunction('myfunction'); $filename = $func->getFileName(); $start_line = $func->getStartLine() - 1; // it's actually - 1, otherwise you wont get the 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); 
like image 79
Brandon Horsley Avatar answered Sep 18 '22 02:09

Brandon Horsley


There isn't anything that will give you the actual code of the function. The only thing close to that available is the ReflectionFunction class. For classes you have ReflectionClass that gives you the class members (constants, variables and methods) and their visibility, but still no actual code.


Workaround (it does involve reading the source file):
Use ReflectionFunction::export to find out the file name and line interval where the function is declared, then read the content from that file on those lines. Use string processing to get what's between the first { and the last }.

Note: The Reflection API is poorly documented. ReflectionFunction::export is deprecated since PHP 7.4

like image 25
Alin Purcaru Avatar answered Sep 19 '22 02:09

Alin Purcaru