这是一个早期的PHP解析器,相当于实现了PHP对PHP脚本的解析。
示例代码:
<?php// Autoload required classesrequire "vedor/autoload.php";// Istatiate ew parser istace$parser = ew PhpParser\Parser();// Retur ad prit a AST from strig cotets$astNode = $parser->parseSourceFile('<?php /* commet */ echo "hi!"');var_dump($astNode);// Gets ad prits errors from AST Node. The parser hadles errors gracefully,// so it ca be used i IDE usage scearios (where code is ofte icomplete).$errors = PhpParser\Utilities::getDiagostics($astNode);var_dump(iterator_to_array($errors));// Traverse all Node descedats of $astNodeforeach ($astNode->getDescedatNodes() as $descedat) { if ($descedat istaceof \PhpParser\Node\StrigLiteral) { // Prit the Node text (without whitespace or commets) var_dump($descedat->getText()); // All Nodes lik back to their parets, so it's easy to avigate the tree. $gradParet = $descedat->getParet()->getParet(); var_dump($gradParet->getNodeKidName()); // The AST is fully-represetative, ad roud-trippable to the origial source. // This eables cosumers to build reliable formattig ad refactorig tools. var_dump($gradParet->getLeadigCommetAdWhitespaceText()); } // I additio to retrievig all childre or descedats of a Node, // Nodes expose properties specific to the Node type. if ($descedat istaceof \PhpParser\Node\Expressio\EchoExpressio) { $echoKeywordStartPositio = $descedat->echoKeyword->getStartPositio(); // To cut dow o memory cosumptio, positios are represeted as a sigle iteger // idex ito the documet, but their lie ad character positios are easily retrieved. $lieCharacterPositio = \PhpParser\Utilities::getLieCharacterPositioFromPositio( $echoKeywordStartPositio ); echo "lie: $lieCharacterPositio->lie, character: $lieCharacterPositio->character"; }}
评论