PHP › Static Analysis (PHPStan & Psalm)

What is static analysis, and how do tools like PHPStan and Psalm help catch bugs in PHP code before it is even run?

Beginner

Answer

Static analysis is the process of examining source code without actually executing it, looking for patterns that indicate likely bugs, such as calling a method that does not exist, passing the wrong data type to a function, or referencing a variable that was never defined, and tools like PHPStan and Psalm scan an entire codebase this way, catching many categories of mistakes that would otherwise only be discovered later at runtime, potentially in production, helping developers fix issues much earlier and with much greater confidence in their code's correctness.
vendor/bin/phpstan analyse src/
Real-world example A development team runs PHPStan against their entire codebase before every deployment, automatically catching a typo in a method name that would have otherwise only surfaced as an error once a specific rarely used feature was actually triggered by a real user.

Common follow-ups: Can static analysis catch every possible bug in an application?;How does static analysis differ from unit testing in terms of what kinds of issues each one catches?