PHP-Parser

nikicBSD-3-Clause活跃维护

用 PHP 写的 PHP 解析器,能把源码转成 AST,方便做静态分析、代码改写和工具链开发。

A PHP parser written in PHP

v5.9.0发布于 2026-09-13 18:55 UTC17,475star +4 / 7 天1,143fork同步于 2026-11-10 11:25 UTC

怎么上手

由 README 提炼,执行前请确认
php composer.phar require nikic/php-parser
硬件要求按 README 说明

README 未说明,纯 PHP 库,无 GPU 或显存要求;5.x 需运行在 PHP >= 7.4 上

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 PHP 写的 PHP 解析器,把 PHP 代码转成 AST,方便做静态分析和代码改写

用 PHP 写的 PHP 解析器,能把源码转成 AST,方便做静态分析、代码改写和工具链开发。

核心能力

  • 把 PHP 7/8 代码解析成带精确位置信息的 AST
  • 语法错误的代码也能解析出部分 AST
  • 把 AST 还原成 PHP 代码,并保留未改动部分的格式
  • 提供遍历、修改 AST 的访问器与节点查找 API
  • 支持命名空间名称解析与常量表达式求值

容易踩的坑

5.x 要求 PHP >= 7.4,旧环境需改用 4.x 分支;解析 PHP 5.x 代码仅有限支持;性能文档提示 Xdebug 会影响速度,建议关闭

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v5.9.0
  1. v5.9.0PHP-Parser 5.9.0最新正式版2026-09-13 · 2026-09-13 18:55 UTC

    Fixed

    • Fix attribute insertion on enums and enum cases in formatting-preserving pretty printer.
    • Reject invalid Unicode escapes above \u{10FFFF}. Previously the limit was \u{1FFFFF}.
    • Don't allow newlines in (void) cast emulation.
    • Fix warning on float hex/binary/octal literals with PHP 8.6.

    Added

    • Added support for PHP 8.6 partial function application. Placeholders are represented using ArgPlaceholder nodes.
  2. v5.8.0PHP-Parser 5.8.02026-07-04 · 2026-07-04 14:33 UTC
    查看更新说明

    Fixed

    • Treat _ as label character in formatting-preserving pretty printer.
    • Handle comment after object operator in keyword emulator.

    Changed

    • Drop support for pipe operator in constant expression evaluator. It is not supported in constant expressions and may pose security risks, as it allows calls to arbitrary functions.
    • void parameter types now generate a (recoverable) error during parsing.
    • Restored reverse emulation support for fn keywords when targeting PHP before 7.4.
  3. v5.7.0PHP-Parser 5.7.02025-12-06 · 2025-12-06 11:57 UTC
    查看更新说明

    Fixed

    • Fixed changing modifier on anonymous class with formatting preserving pretty printer.
    • Emit an error for unparenthesized arrow functions in pipe operator, and print necessary parentheses in the pretty printer.
    • Fix PHP 8.5 deprecation warning in php-parse binary.

    Changed

    • When targeting PHP 8.4 or newer, omit parentheses around immediately dereferenced new expressions.

    Added

    • Added shouldPrintRawValue attribute to Scalar\Int_, which makes the pretty printer use the rawValue of the node. This can be used to print integers with separators.
  4. v4.19.5PHP-Parser 4.19.52025-12-06 · 2025-12-06 11:46 UTC
    查看更新说明

    Fixed

    • Fixed deprecation warnings on PHP 8.5.
  5. v5.6.2PHP-Parser 5.6.22025-10-21 · 2025-10-21 19:33 UTC
    查看更新说明

    Fixed

    • Fixed formatting-preserving pretty-printing when changing the visibility modifier on a node that has attributes.
    • Fixed chr() deprecation warning on PHP 8.5.

    Added

    • Added Param::isFinal() method.

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    PHP Parser

    Coverage Status

    This is a PHP parser written in PHP. Its purpose is to simplify static code analysis and manipulation.

    Documentation for version 5.x (current; for running on PHP >= 7.4; for parsing PHP 7.0 to PHP 8.4, with limited support for parsing PHP 5.x).

    Documentation for version 4.x (supported; for running on PHP >= 7.0; for parsing PHP 5.2 to PHP 8.3).

    Features

    The main features provided by this library are:

    • Parsing PHP 7, and PHP 8 code into an abstract syntax tree (AST).
      • Invalid code can be parsed into a partial AST.
      • The AST contains accurate location information.
    • Dumping the AST in human-readable form.
    • Converting an AST back to PHP code.
      • Formatting can be preserved for partially changed ASTs.
    • Infrastructure to traverse and modify ASTs.
    • Resolution of namespaced names.
    • Evaluation of constant expressions.
    • Builders to simplify AST construction for code generation.
    • Converting an AST into JSON and back.

    Quick Start

    Install the library using composer:

    php composer.phar require nikic/php-parser
    

    Parse some PHP code into an AST and dump the result in human-readable form:

    <?php
    use PhpParser\Error;
    use PhpParser\NodeDumper;
    use PhpParser\ParserFactory;
    
    $code = <<<'CODE'
    <?php
    
    function test($foo)
    {
        var_dump($foo);
    }
    CODE;
    
    $parser = (new ParserFactory())->createForNewestSupportedVersion();
    try {
        $ast = $parser->parse($code);
    } catch (Error $error) {
        echo "Parse error: {$error->getMessage()}\n";
        return;
    }
    
    $dumper = new NodeDumper;
    echo $dumper->dump($ast) . "\n";
    

    This dumps an AST looking something like this:

    array(
        0: Stmt_Function(
            attrGroups: array(
            )
            byRef: false
            name: Identifier(
                name: test
            )
            params: array(
                0: Param(
                    attrGroups: array(
                    )
                    flags: 0
                    type: null
                    byRef: false
                    variadic: false
                    var: Expr_Variable(
                        name: foo
                    )
                    default: null
                )
            )
            returnType: null
            stmts: array(
                0: Stmt_Expression(
                    expr: Expr_FuncCall(
                        name: Name(
                            name: var_dump
                        )
                        args: array(
                            0: Arg(
                                name: null
                                value: Expr_Variable(
                                    name: foo
                                )
                                byRef: false
                                unpack: false
                            )
                        )
                    )
                )
            )
        )
    )
    

    Let's traverse the AST and perform some kind of modification. For example, drop all function bodies:

    use PhpParser\Node;
    use PhpParser\Node\Stmt\Function_;
    use PhpParser\NodeTraverser;
    use PhpParser\NodeVisitorAbstract;
    
    $traverser = new NodeTraverser();
    $traverser->addVisitor(new class extends NodeVisitorAbstract {
        public function enterNode(Node $node) {
            if ($node instanceof Function_) {
                // Clean out the function body
                $node->stmts = [];
            }
        }
    });
    
    $ast = $traverser->traverse($ast);
    echo $dumper->dump($ast) . "\n";
    

    This gives us an AST where the Function_::$stmts are empty:

    array(
        0: Stmt_Function(
            attrGroups: array(
            )
            byRef: false
            name: Identifier(
                name: test
            )
            params: array(
                0: Param(
                    attrGroups: array(
                    )
                    type: null
                    byRef: false
                    variadic: false
                    var: Expr_Variable(
                        name: foo
                    )
                    default: null
                )
            )
            returnType: null
            stmts: array(
            )
        )
    )
    

    Finally, we can convert the new AST back to PHP code:

    use PhpParser\PrettyPrinter;
    
    $prettyPrinter = new PrettyPrinter\Standard;
    echo $prettyPrinter->prettyPrintFile($ast);
    

    This gives us our original code, minus the var_dump() call inside the function:

    <?php
    
    function test($foo)
    {
    }
    

    For a more comprehensive introduction, see the documentation.

    Documentation

    1. Introduction
    2. Usage of basic components

    Component documentation:

    • Walking the AST
      • Node visitors
      • Modifying the AST from a visitor
      • Short-circuiting traversals
      • Interleaved visitors
      • Simple node finding API
      • Parent and sibling references
    • Name resolution
      • Name resolver options
      • Name resolution context
    • Pretty printing
      • Converting AST back to PHP code
      • Customizing formatting
      • Formatting-preserving code transformations
    • AST builders
      • Fluent builders for AST nodes
    • Lexer
      • Emulation
      • Tokens, positions and attributes
    • Error handling
      • Column information for errors
      • Error recovery (parsing of syntactically incorrect code)
    • Constant expression evaluation
      • Evaluating constant/property/etc initializers
      • Handling errors and unsupported expressions
    • JSON representation
      • JSON encoding and decoding of ASTs
    • Performance
      • Disabling Xdebug
      • Reusing objects
      • Garbage collection impact
    • Frequently asked questions
      • Parent and sibling references