reflection - How to extract start line of a property declaration in PHP? -
with reflection, it's easy start , end line e.g. of method in source file: reflectionfunctionabstract::getfilename()
, reflectionfunctionabstract::getstartline()
, reflectionfunctionabstract::getendline()
provide functionality. however, doesn't seem work properties. what's best way extract @ least start line , file name of property declaration in class definition?
it's not trivial not hard.
you can class property defined in via reflection. , there can filename. have either tokenize file , check @ line property declaration or go on file line line , string matching.
here 1 possible way that:
$reflector = new reflectionproperty('foo', 'bar'); $declaringclass = $reflector->getdeclaringclass(); $classfile = new splfileobject($declaringclass->getfilename()); foreach ($classfile $line => $content) { if (preg_match( '/ (private|protected|public|var) # match visibility or var \s # followed 1 whitespace \$bar # followed var name $bar /x', $content) ) { echo $line + 1; } }
and here demo show works
obviously, above solution assumes property declared in fashion. assumes have 1 class per file. if cannot sure case, tokenization better option. it's more difficult.
Comments
Post a Comment