php-ast icon indicating copy to clipboard operation
php-ast copied to clipboard

[question] How to list all classes that used in a file?

Open erlangparasu opened this issue 3 years ago • 2 comments

For example:

class MyKlass {
    public function createBook()
    {
        $book = new Book();

        return $book;
    }

    public function formatter()
    {
        $formatter = Utils::getFormatter();

        return $formatter;
    }
}

How to print list of class usage of that file? In this example expected output will be: "Book" and "Utils" class. Thanks

erlangparasu avatar Sep 09 '22 07:09 erlangparasu

Currently i found: Stmt_Class, Expr_StaticCall, Name_FullyQualified and Expr_New to able to find class usage.

Any other possible keyword to check? Thanks

erlangparasu avatar Sep 09 '22 07:09 erlangparasu

There's a lot of them - there's also AST_USE/AST_GROUP_USE which would tell you what use Xyz\Foo; meant Foo was.

You may want to use a static analyzer instead, e.g. https://github.com/phan/phan

For example, https://github.com/phan/phan/blob/5.2.1/tool/pdep#L20-L54 would print the full dependency graph of classes


Currently i found: Stmt_Class, Expr_StaticCall, Name_FullyQualified and Expr_New to able to find class usage.

Are you thinking of https://github.com/nikic/php-parser and https://github.com/nikic/PHP-Parser/tree/master/lib/PhpParser/Node/Stmt

TysonAndre avatar Sep 17 '22 22:09 TysonAndre