PHPStan reference
21 August 2024 (Updated 21 August 2024)
In a nutshell
PHPStan is a linter for PHP, similar to ESLint for JavaScript.
Install
composer require --dev phpstan/phpstan
Analyse using config file
Ensure you have a phpstan.neon
or phpstan.neon.dist
file and run:
vendor/bin/phpstan
Create config file (phpstan.neon
)
Minimal config file:
parameters:
level: 9
paths:
- src
- tests
Analyse with default rule (0)
vendor/bin/phpstan analyse <directories>
Analyse with specific rule
vendor/bin/phpstan analyse -l <0-9> directories
Configure rules
You can choose a level from 0 to 9 (0 is the loosest and 9 is the highest):
- 0. basic checks, unknown classes, unknown functions, unknown methods called on $this, wrong number of arguments passed to those methods and functions, always undefined variables
- 1. possibly undefined variables, unknown magic methods and properties on classes with call and get
- 2. unknown methods checked on all expressions (not just $this), validating PHPDocs
- 3. return types, types assigned to properties
- 4. basic dead code checking – always false instanceof and other type checks, dead else branches, unreachable code after return; etc.
- 5. checking types of arguments passed to methods and functions
- 6. report missing typehints
- 7. report partially wrong union types – if you call a method that only exists on some types in a union type, level 7 starts to report that; other possibly incorrect situations
- 8. report calling methods and accessing properties on nullable types
- 9. be strict about the mixed type – the only allowed operation you can do with it is to pass it to another mixed
Add more strictness
Install the phpstan/phpstan-strict-rules
package:
Tagged:
PHP tooling
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment