- preg_match: documentation ( source)
- preg_quote: documentation ( source)
- feof: documentation ( source)
- fgets: documentation ( source)
- sprintf: documentation ( source)
- fopen: documentation ( source)
<?php
$re = new ReflectionClass(A::class);
extractMethodBody($re->getMethod('a'));
/**
* @param \ReflectionMethod $method
* @return string
*/
function extractMethodBody(\ReflectionMethod $method)
{
$startLine = $method->getStartLine();
$endLine = $method->getEndLine() + 1;
$resource = fopen($method->getFileName(), 'r');
$currentLine = 0;
while (!feof($resource) && ++$currentLine < $startLine) {
fgets($resource, 1024);
}
$buffer = '';
while (!feof($resource) && ++$currentLine <= $endLine) {
$buffer .= fgets($resource, 1024);
}
preg_match(sprintf('/(?:public|protected|private|final|abstract|static)*?'
. '\s+function\s+%s\([^\)]*\)\s*(?:\{(?:[^{}]*|(?R))*\})/sm', preg_quote($method->getName())),
$buffer, $matches
);
return $matches[0];
}
class A
{
public function test(stdClass $b)
{
return $b;
}
}