What it is
PHPStan is a static analysis tool for PHP that finds type errors, undefined methods and impossible conditions without running the code.
Configure paths and a level in phpstan.neon. Raise the level gradually; a baseline file freezes existing errors so only new ones fail.
Installation
composer require --dev phpstan/phpstanGetting started
The smallest useful thing you can do with it, and what each part means.
parameters:
level: 8 # 0 is lenient, 10 is strictest
paths:
- src
- tests
excludePaths:
- src/Generated
treatPhpDocTypesAsCertain: false
baseline: phpstan-baseline.neon
includes:
- vendor/phpstan/phpstan-strict-rules/rules.neon
# Freeze existing errors on a legacy codebase:
# vendor/bin/phpstan analyse --generate-baselineAdvanced usage
Where the library earns its place over a simpler alternative.
php
<?php
/**
* PHP has no generics, but PHPStan understands them in docblocks.
*
* @template T of object
* @param class-string<T> $className
* @return T
*/
function make(string $className): object
{
return new $className();
}
$book = make(Book::class); // PHPStan knows this is a Book
/**
* @param array{title: string, year: int, tags?: list<string>} $data
* @return non-empty-list<Book>
*/
function createBooks(array $data): array { /* … */ }Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- Thousands of errors on the first run
- Start at level 0, or generate a baseline. Raising the level gradually is the intended workflow.
- Call to an undefined method on a framework class
- Magic methods are invisible to static analysis. Install the framework's PHPStan extension.
Best practices
- Generate a baseline on an existing project, then raise the level incrementally.
- Run at level 8 or higher on new code; below level 5 catches comparatively little.
- Add the framework extension (phpstan-symfony, larastan) so magic methods are understood.
- Never silence errors with @phpstan-ignore without a comment explaining why.
Background
Why it exists, and what it was reacting to.
PHPStan gives PHP much of the safety a compiler provides in typed languages. Its level system, from 0 to 10, makes adoption on an existing codebase realistic rather than overwhelming.
