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/
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With