PHPStan checks source-level type compatibility, nullable values and PHPDoc contracts without launching application routes.
What It Does
Analyze application source with the project-local PHPStan binary. A typed associative array allows checks of keys and values.
Requirements and Compatibility
Use a supported PHP runtime and install any third-party tool or extension explicitly shown in the examples. Commands should be run from the project root unless stated otherwise.
Syntax, Inputs and Results
The examples separate configuration, the smallest working operation and a realistic follow-up task. Adapt file paths and dependency versions to your own project.
Example 1: Basic Use
Analyze application source with the project-local PHPStan binary.
composer require --dev phpstan/phpstan
vendor/bin/phpstan analyse src --no-progress
Example 2: Another Case
A typed associative array allows checks of keys and values.
<?php
/** @param array<string, int> $inventory */
function remaining(array $inventory, string $sku): int {
return $inventory[$sku] ?? 0;
}
echo remaining(["A1" => 7], "A1");
Practical Example
Include both production and test source paths in analysis.
parameters:
level: 7
paths:
- src
- tests
For production, apply the compatibility and edge-case limits described below.
Important Behavior and Edge Cases
Static analysis complements PHPUnit and cannot prove that a calculation is correct at runtime.
Comparison with Related Functions and Tools
| Subject | Key difference |
|---|---|
| Static analysis vs runtime tests | PHPStan checks source types without executing business behavior; tests confirm actual outcomes. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring unknown or mixed types | Add valid PHPDoc element types or proper native declarations, then re-run the analyzer. |
| Skipping the prerequisite of this specific workflow | Install or configure the named tool and confirm the example can actually run. |
| Ignoring edge conditions | Static analysis complements PHPUnit and cannot prove that a calculation is correct at runtime. |
Key Takeaways
- PHPStan checks source-level type compatibility, nullable values and PHPDoc contracts without launching application routes.
- Static analysis complements PHPUnit and cannot prove that a calculation is correct at runtime.
- Keep application configuration, source code and validation tests under version control.
Use these examples as a starting point, then validate the result with the actual PHP build, dependencies and inputs used by your application.