PHP 8: Modern PHP Development · Testing and Tooling

Static Analysis with PHPStan and Psalm

Find bugs before running code and adopt strict levels gradually.

PHPStan and Psalm analyze code without running it, catching undefined methods, wrong types, null access and dead code. They understand PHPDoc generics (array<int, User>, list<string>, Collection<User>) and framework plugins (Larastan for Laravel, phpstan-symfony, phpstan-doctrine). Start at a low level, generate a baseline for existing errors, and raise levels over time so new code is held to the strictest standard.

# phpstan.neon
parameters:
  level: 8
  paths:
    - src
    - tests
includes:
  - phpstan-baseline.neon
/**
 * @param list<OrderLine> $lines
 * @return array<string, int> totals keyed by currency
 */
function totalsByCurrency(array $lines): array { /* ... */ }
vendor/bin/phpstan analyse --generate-baseline   # accept current errors, block new ones
vendor/bin/phpstan analyse

Common pitfalls

  • Ignoring errors with broad ignoreErrors patterns instead of fixing or baselining.
  • Missing framework extensions, causing false positives on magic methods.
  • Never revisiting the baseline.

Key points

  • Catch type and null bugs before runtime
  • Use generics in PHPDoc
  • Baseline legacy errors, raise levels gradually

Further reading: PHPStan user guide

Practice questions

What is a PHPStan baseline?

Answer

A file listing existing errors to ignore, so you can adopt a strict level on a legacy codebase while failing CI only on new errors. Shrink it over time.

Why add @param list<User> when the parameter is typed array?

Answer

Native array says nothing about element types. The PHPDoc generic tells analyzers and IDEs what's inside, enabling checks on element access.

Open in the app to mark lessons complete, take notes and track your progress.