1Frequently Asked Questions 2========================== 3 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) 6 7How can the parent of a node be obtained? 8----- 9 10The AST does not store parent nodes by default. However, the `ParentConnectingVisitor` can be used to achieve this: 11 12```php 13use PhpParser\NodeTraverser; 14use PhpParser\NodeVisitor\ParentConnectingVisitor; 15use PhpParser\ParserFactory; 16 17$code = '...'; 18 19$traverser = new NodeTraverser(new ParentConnectingVisitor); 20 21$parser = (new ParserFactory())->createForHostVersion(); 22$ast = $parser->parse($code); 23$ast = $traverser->traverse($ast); 24``` 25 26After running this visitor, the parent node can be obtained through `$node->getAttribute('parent')`. 27 28How can the next/previous sibling of a node be obtained? 29----- 30 31Again, siblings are not stored by default, but the `NodeConnectingVisitor` can be used to store 32the previous / next node with a common parent as well: 33 34```php 35use PhpParser\NodeTraverser; 36use PhpParser\NodeVisitor\NodeConnectingVisitor; 37use PhpParser\ParserFactory; 38 39$code = '...'; 40 41$traverser = new NodeTraverser(new NodeConnectingVisitor); 42 43$parser = (new ParserFactory())->createForHostVersion(); 44$ast = $parser->parse($code); 45$ast = $traverser->traverse($ast); 46``` 47 48After running this visitor, the parent node can be obtained through `$node->getAttribute('parent')`, 49the previous node can be obtained through `$node->getAttribute('previous')`, and the next node can be 50obtained through `$node->getAttribute('next')`. 51 52`ParentConnectingVisitor` and `NodeConnectingVisitor` should not be used at the same time. The latter 53includes the functionality of the former. 54