如何在 PHP 中提取属性声明的起始行? [英] How to extract start line of a property declaration in PHP?

查看:48
本文介绍了如何在 PHP 中提取属性声明的起始行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过反射,很容易得到开始和结束行,例如源文件中的一个方法: ReflectionFunctionAbstract::getFileName(), ReflectionFunctionAbstract::getStartLine(), ReflectionFunctionAbstract::getEndLine() 提供这个功能.但是,这似乎不适用于属性.在类定义中至少提取属性声明的起始行和文件名的最佳方法是什么?

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?

推荐答案

这不是微不足道的,也不是太难.

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.

这是一种可能的方法:

$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;
    }
}

这里有一个 演示来证明它是有效的

显然,上述解决方案假定要以某种方式声明该属性.它还假设每个文件有一个类.如果您不能确定是这种情况,标记化是更好的选择.但也更难.

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.

这篇关于如何在 PHP 中提取属性声明的起始行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆