With reflection, it's easy to get the start and end line e.g. of a method in the source file: ReflectionFunctionAbstract::getFileName()
, ReflectionFunctionAbstract::getStartLine()
, ReflectionFunctionAbstract::getEndLine()
provide this functionality. However, this doesn't seem to work with properties. What's the best way to extract at least the start line and the file name of a property declaration in a class definition?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
It's not trivial but also not too hard.
You can get the class a property is defined in via Reflection. And from there you can get the filename. All you have to do then is either tokenize the file and check at what line the property declaration or simply go over the file line by line and do string matching.
Here is one possible way to do that:
$reflector = new ReflectionProperty('Foo', 'bar');
$declaringClass = $reflector->getDeclaringClass();
$classFile = new SplFileObject($declaringClass->getFileName());
foreach ($classFile as $line => $content) {
if (preg_match(
'/
(private|protected|public|var) # match visibility or var
\s # followed 1 whitespace
\$bar # followed by the var name $bar
/x',
$content)
) {
echo $line + 1;
}
}
And here is a demo to show that it works
Obviously, the above solution assumes the property to be declared in a certain fashion. It also assumes you have one class per file. If you cannot be sure this is the case, tokenization is the better option. But it's also more difficult.