QA
Senior LevelPHP 8+

How do static analysis tools (PHPStan, Psalm) traverse the PHP Abstract Syntax Tree (AST) to detect bugs?

❓ Interview Prompt: Explain PHP Abstract Syntax Tree (AST), nikic/php-parser, type inference engines, and static analysis with PHPStan and Psalm.

Static analysis tools like PHPStan and Psalm analyze PHP source code for bugs, type errors, and dead code without running the scripts.

How AST Static Analysis Works:

1
Parser Phase: Converts raw PHP code into an Abstract Syntax Tree (AST) node hierarchy using 'nikic/php-parser' or the native 'ext-ast' extension.
2
Type Inference Engine: Traverses AST nodes, tracking variable types through 'if/else' branches, loops, and docblock annotations.
3
Bug Detection: Detects undefined method calls, type mismatches, potential 'null' dereferences, and unreachable dead code before deployment!

Code Implementation Example

php
<?php
// Custom AST Node Visitor inspecting code for eval() usage using nikic/php-parser
use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;

class SecurityRuleVisitor extends NodeVisitorAbstract {
    public function leaveNode(Node $node) {
        if ($node instanceof Node\Expr\Eval_) {
            echo "SECURITY WARNING: Use of eval() detected on line " . $node->getLine() . "
";
        }
    }
}
💡Custom AST Node Visitor inspecting PHP code for dangerous functions using nikic/php-parser.
🎯 Interview Key Takeaway

PHPStan and Psalm parse code into Abstract Syntax Trees (ASTs), running type inference engines to detect bugs without executing scripts.

#AST#PHPStan#Psalm#Static Analysis#Senior
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?