How to get variable value using Nikic/PHPParser

250 views Asked by At

I have the following PHP code file:

<?php
class ObjectTest extends AppTest
{
    public function getList()
    {
        return [
            '1234',
            '5678',
        ];
    }
}

Now I like to use nikic/PHP-Parser to get the return value of the getList function

How do I do that?

1

There are 1 answers

0
Jeto On

The following would do it:

$parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);

try {
    $ast = $parser->parse($code);
} catch (Error $error) {
    // Handle error...
}

$class = $ast[0];

$method = $class->getMethod('getList');

$returnStatement = $method->getStmts()[0];

$returnedValues = array_map(fn($item) => $item->value->value, $returnStatement->expr->items);

print_r($returnedValues);  // [1234, 5678]

Demo