How to extract start line of a property declaratio

2019-07-04 05:22发布

问题:

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.