获取 PHP AST 节点种类

Get PHP AST node kind

设置后$ast = ast\parse_code('<?php $a=1;', $version=50);

我可以看到节点的内容,但想知道节点的确切类型。我看到的输出只是给出了分配的种类常量的整数值——有没有办法找出它指的是哪种种类(即获取常量的名称)?

php > var_dump($ast);
object(ast\Node)#1 (4) {
  ["kind"]=>
  int(132)
  ["flags"]=>
  int(0)
  ["lineno"]=>
  int(1)
  ["children"]=>
  array(1) {
    [0]=>
    object(ast\Node)#2 (4) {
      ["kind"]=>
      int(517)
      ["flags"]=>
      int(0)
      ["lineno"]=>
      int(1)
      ["children"]=>
      array(2) {
        ["var"]=>
        object(ast\Node)#3 (4) {
          ["kind"]=>
          int(256)
          ["flags"]=>
          int(0)
          ["lineno"]=>
          int(1)
          ["children"]=>
          array(1) {
            ["name"]=>
            string(1) "a"
          }
        }
        ["expr"]=>
        int(1)
      }
    }
  }
}

如果您知道要查找的节点类型,则可以与给定类型进行比较,即

$node->kind === \ast\AST_ASSIGN

但是,对于一般名称查找,库提供了 ast\get_kind_name() (source)。例如:

php > echo \ast\get_kind_name(517);
AST_ASSIGN

如果您想要一种更简单的方式来查看 AST,该库提供了一个 util.php 文件(source) with a function that dumps out the AST. Details on using it can be found below the first example in this section(在此处复制)。

require 'path/to/util.php';
echo ast_dump(ast\parse_code('<?php $a=1;', $version=50)), "\n";