1 Frequently Asked Questions
2 ==========================
4 * [How can the parent of a node be obtained?](#how-can-the-parent-of-a-node-be-obtained)
5 * [How can the next/previous sibling of a node be obtained?](#how-can-the-nextprevious-sibling-of-a-node-be-obtained)
7 How can the parent of a node be obtained?
10 The AST does not store parent nodes by default. However, it is easy to add a custom parent node
11 attribute using a custom node visitor:
15 use PhpParser\NodeVisitorAbstract;
17 class ParentConnector extends NodeVisitorAbstract {
19 public function beforeTraverse(array $nodes) {
22 public function enterNode(Node $node) {
23 if (!empty($this->stack)) {
24 $node->setAttribute('parent', $this->stack[count($this->stack)-1]);
26 $this->stack[] = $node;
28 public function leaveNode(Node $node) {
29 array_pop($this->stack);
34 After running this visitor, the parent node can be obtained through `$node->getAttribute('parent')`.
36 How can the next/previous sibling of a node be obtained?
39 Again, siblings are not stored by default, but the visitor from the previous entry can be easily
40 extended to store the previous / next node with a common parent as well:
44 use PhpParser\NodeVisitorAbstract;
46 class NodeConnector extends NodeVisitorAbstract {
49 public function beforeTraverse(array $nodes) {
53 public function enterNode(Node $node) {
54 if (!empty($this->stack)) {
55 $node->setAttribute('parent', $this->stack[count($this->stack)-1]);
57 if ($this->prev && $this->prev->getAttribute('parent') == $node->getAttribute('parent')) {
58 $node->setAttribute('prev', $this->prev);
59 $this->prev->setAttribute('next', $node);
61 $this->stack[] = $node;
63 public function leaveNode(Node $node) {
65 array_pop($this->stack);