nikic/php-ast

Navigating up from child

zenoware opened this issue · 2 comments

First off, this is amazing!! Great work and very easy to use! Thank you to all the contributors of this because it rocks!

I attempted to look through the code and documentation and could not find a way to go from a child node to it's parent.

Some insight, I am attempting to do this in order to get the fully qualified name.

Thanks!

nikic commented

The AST does not have parent references by default, but you should be able to easily add them yourself using something like this:

function add_parents(ast\Node $node, ast\Node $parent = null) {
    $node->parent = $parent;
    foreach ($node->children as $child) {
        if ($child instanceof ast\Node) {
            add_parents($child, $node);
        }
    }
}

Btw, unless you need to use php-ast for performance reasons, I'd usually recommend using https://github.com/nikic/PHP-Parser. It already implements the resolution for namespaced names (which is a lot trickier than people tend to think...)

Thanks for the response and I will check out this solution plus PHP-Parser. Yeah I figured it will be a tough task. So far I have been having a fantastic experience with php-ast! Using it to create a static code analysis and php is the latest language I am including. This package is making it a breeze!