What’s New in PHP‑Parser 5.0.0? A Deep Dive into Features and Usage

PHP‑Parser 5.0.0 introduces a host of new classes, methods, and parser improvements—including a PhpVersion class, PHP 8 support, enhanced pretty‑printing, and updated node handling—while also deprecating older APIs; the article provides a detailed changelog and a concise usage example for parsing PHP code.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
What’s New in PHP‑Parser 5.0.0? A Deep Dive into Features and Usage
PHP‑Parser is a pure‑PHP library (by nikic) that parses PHP code from version 5.2 up to 8.3, simplifying static analysis and source‑code manipulation for PHP developers.

5.0.0 Release Highlights

Added

PhpVersion class for finer control of target PHP version, accepted by ParserFactory, Parser, Lexer, PrettyPrinter.

PHP8 parser (difference from PHP7 parser is only operator precedence).

Parser::getTokens() method.

Modifiers class as replacement for Stmt\Class_::MODIFIER_*.

NodeVisitor::enterNode() can now return an array or REMOVE_NODE.

Many extra type annotations now used by PhpStan.

Fuzz target added to PHP‑Fuzzer, exposing printer bugs.

Param now has isPromoted(), isPublic(), isProtected(), isPrivate(), isReadonly() methods.

Trait builder now supports class constants.

PrettyPrinter interface added.

Support for preserving formatting when toggling static modifiers.

php-parse binary now accepts “‑” as filename to read from stdin.

Support for NodeVisitor::REPLACE_WITH_NULL.

Pretty printer now supports CRLF newlines via the newline option.

Visitors can be passed directly to NodeTraverser constructor, removing need for addVisitor().

NodeDumper now prints additional attributes such as kind.

InterpolatedStringPart and heredoc/nowdoc String_ gain rawValue property for the original un‑parsed value.

Stmt\Block node added to represent {} code blocks, preserving nested block structure.

Modified

PHP‑Parser now requires PHP 7.4 to run.

Added property types where possible.

Standard pretty printer output tightened to match PSR‑12.

Internal token representation now uses PhpParser\Token, compatible with PhpToken from PHP 8.

Array destructuring always uses Expr\List_ node, even with [] syntax.

Many node classes renamed; non‑expression/statement content moved out of Expr/Stmt hierarchy, with backward‑compatible aliases.

Pretty printer no longer wraps yield in parentheses unless target version < 7.0.

Pretty printer default target version set to PHP 7.4.

Prints “else if { }” instead of “else { if { } }”.

Visitor leaveNode() now called in reverse order of enterNode().

NodeTraverser::REMOVE_NODE moved to NodeVisitor::REMOVE_NODE (old constant kept for compatibility).

Name node parts replaced by name string; getParts() returns old representation.

Node constructors now require Identifier, Name or ComplexType instead of raw string types.

Comment::getReformattedText() normalises CRLF to LF.

Lexer no longer accepts options; only PhpVersion is accepted. startLexing(), getTokens(), handleHaltCompiler() removed; tokenize() now returns tokens.

Attribute handling moved from lexer to parser; comments, line/position attributes always added.

If target version ≥ 7.3, pretty printer now indents flexible heredoc/nowdoc strings.

Visitor‑based comment assignment now only keeps comments on the outermost node.

NodeDumper performance improved for large dumps.

Removed

PHP 5 parser removed; PHP 7 parser adjusted to handle PHP 5 code more gracefully.

Deprecated Error constructor (takes line number) removed.

Comment::getLine(), getTokenPos(), getFilePos() removed; use getStartLine(), getStartTokenPos(), getStartFilePos() instead.

Stmt\Throw_ node removed; use Stmt\Expression containing Expr\Throw_.

ParserFactory::create() removed.

Fixed

Pretty printer now correctly handles unary operator precedence, adding parentheses only when necessary.

Pretty printer respects clone, throw and arrow‑function precedence.

Fixed formatting preservation for alternative elseif/else syntax.

Fixed safety check for printing strings as heredoc/nowdoc with flexible doc‑string semantics.

Fixed merging of stray \r into CRLF sequences at the end of doc strings.

Fixed handling of very large overflow \u escape sequences.

Formatting printer no longer trims leading spaces.

DEL treated as a label character in formatting printer based on target PHP version.

Fixed error reporting in emulated lexer when no explicit error handler is set.

Graceful handling of non‑contiguous array indexes in Differ.

Deprecated

Node::getLine() deprecated; use Node::getStartLine() instead.

Simple Usage Example

Parsing a short PHP snippet and dumping its AST.
<?php
echo 'Hi', '开源技术小栈';

Write a parsing script

<?php
require __DIR__ . '/../vendor/autoload.php';

$code = <<<'CODE'
<?php

echo 'Hi', '开源技术小栈';

CODE;

$parser = (new \PhpParser\ParserFactory())->createForNewestSupportedVersion();
try {
    $ast = $parser->parse($code);
} catch (\PhpParser\Error $error) {
    echo "Parse error: {$error->getMessage()}
";
    return;
}

$dumper = new \PhpParser\NodeDumper;
echo $dumper->dump($ast) . "
";

Resulting AST

array(
    0: Stmt_Echo(
        exprs: array(
            0: Scalar_String(
                value: Hi
            )
            1: Scalar_String(
                value: 开源技术小栈
            )
        )
    )
)
ASTPHPParserCode Parsingrelease-notes
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.