Get PHP function body as string

This piece of code can return the method body from a class

public static function getFunctionString($class, $function){ $func = new ReflectionMethod($class,$function); $filename = $func->getFileName(); $start_line = $func->getStartLine(); $end_line = $func->getEndLine()-1; $length = $end_line - $start_line; $source = file($filename); $body = implode("", array_slice($source, $start_line, $length)); return $body; }

When to use:

Extract the function details & execute in other another class when the function contains self::func();


class A{ private static $var_a = 1; public static function a(){ self::func(); } public static function func(){ echo self::$var_a; } }

In class B, we need to call function a from Class A

class B{ private static $var_a=2; public static function b(){ eval(getFunctionString('A', 'a')); } } B::b(); //will output 2