xref: /PHP-Parser/doc/component/FAQ.markdown (revision c9d0b6c9)
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
55
56How can I limit the impact of cyclic references in the AST?
57-----
58
59NodeConnectingVisitor adds a parent reference, which introduces a cycle. This means that the AST can now only be collected by the cycle garbage collector.
60This in turn can lead to performance and/or memory issues.
61
62To break the cyclic references between AST nodes `NodeConnectingVisitor` supports a boolean `$weakReferences` constructor parameter.
63When set to `true`, all attributes added by `NodeConnectingVisitor` will be wrapped into a `WeakReference` object.
64
65After enabling this parameter, the parent node can be obtained through `$node->getAttribute('weak_parent')`,
66the previous node can be obtained through `$node->getAttribute('weak_previous')`, and the next node can be
67obtained through `$node->getAttribute('weak_next')`.