PHPStan (often referred to by its Composer package name `phpstan/phpstan`) is a static analysis tool for PHP. It focuses on finding bugs in your code *without running it*. By analyzing your code's abstract syntax tree (AST) and performing sophisticated type inference, PHPStan can detect a wide range of potential issues, from simple type mismatches to more complex logical errors.
Why Use PHPStan?
* Improved Code Quality: Catches errors that might otherwise only appear at runtime, leading to more robust and reliable applications.
* Early Bug Detection: Finds problems during development or in CI/CD pipelines, significantly reducing the cost of fixing them later.
* Better Type Safety: Enforces type hints and infers types where they're missing, helping maintain consistent data flows throughout your application.
* Refactoring Confidence: Provides confidence when refactoring code by ensuring that type contracts are maintained and new changes don't introduce unexpected bugs.
* Self-Documenting Code: Encourages better use of type hints and PHPDoc annotations, making code easier to understand and maintain for current and future developers.
How It Works:
PHPStan parses your PHP code into an Abstract Syntax Tree (AST). It then traverses this tree, applying a set of predefined rules and performing advanced type inference. For example, if a function is declared to return an `int` but its implementation always returns a `string`, PHPStan will flag this as an error. It understands complex object-oriented concepts, generics, and even some advanced PHP features, allowing it to predict potential runtime issues.
Key Features:
* Levels: PHPStan offers different "rule levels" (0-9, with 9 being the strictest). Starting at a lower level and gradually increasing it allows for incremental adoption, especially in existing or legacy projects.
* Custom Rules: You can write your own custom rules to enforce project-specific coding standards, detect unique patterns, or integrate with domain-specific logic.
* Baselines: For large legacy projects with many existing issues, a "baseline" file can be generated to ignore current errors, allowing new code to be checked strictly without overwhelming the developer with old issues.
* Integration: Easily integrates with Composer, various Integrated Development Environments (IDEs), and Continuous Integration/Continuous Deployment (CI/CD) pipelines.
Installation:
PHPStan is typically installed as a development dependency using Composer:
`composer require --dev phpstan/phpstan`
Usage:
After installation, you can run PHPStan from your project root:
`vendor/bin/phpstan analyse <path/to/your/code>`
You can also provide a configuration file (`phpstan.neon` or `phpstan.neon.dist`) to specify rule levels, ignored paths, custom rules, and more.
Example Code
```php
# 1. Project Setup (Run in your terminal)
# Create a new project directory
# mkdir phpstan-example
# cd phpstan-example
# Initialize Composer
# composer init --no-interaction # Press enter for defaults
# Install PHPStan as a dev dependency
# composer require --dev phpstan/phpstan
# 2. Create the source file with a deliberate error (src/Calculator.php)
# file: src/Calculator.php
<?php
namespace App;
class Calculator
{
/
* Adds two integers.
* @param int $a The first integer.
* @param int $b The second integer.
* @return int The sum of the two integers.
*/
public function add(int $a, int $b): int
{
// Deliberate error: returning a string instead of an integer
return (string)($a + $b);
}
/
* Divides two integers.
* @param int $numerator The numerator.
* @param int $denominator The denominator (cannot be zero).
* @return float The result of the division.
*/
public function divide(int $numerator, int $denominator): float
{
if ($denominator === 0) {
// In a real application, you might throw an exception here.
// For this example, returning 0.0 is valid for the float return type.
return 0.0;
}
return $numerator / $denominator;
}
}
# 3. Create a PHPStan configuration file (phpstan.neon)
# file: phpstan.neon
parameters:
level: 5 # A moderate rule level for demonstration
paths:
- src # Tells PHPStan to analyze the 'src' directory
# 4. Run PHPStan from your terminal
# vendor/bin/phpstan analyse
# Expected PHPStan Output (illustrating the error):
# ------ ---------------------------------------------------------------------------------------------
# Line src/Calculator.php
# ------ ---------------------------------------------------------------------------------------------
# 18 Method App\Calculator::add() should return int but returns string.
# ------ ---------------------------------------------------------------------------------------------
#
# [ERROR] Found 1 error
# 5. Corrected source file (src/Calculator.php)
# file: src/Calculator.php
<?php
namespace App;
class Calculator
{
/
* Adds two integers.
* @param int $a The first integer.
* @param int $b The second integer.
* @return int The sum of the two integers.
*/
public function add(int $a, int $b): int
{
// Corrected: returns an integer as expected
return $a + $b;
}
/
* Divides two integers.
* @param int $numerator The numerator.
* @param int $denominator The denominator (cannot be zero).
* @return float The result of the division.
*/
public function divide(int $numerator, int $denominator): float
{
if ($denominator === 0) {
return 0.0;
}
return $numerator / $denominator;
}
}
# 6. Run PHPStan again (after correction)
# vendor/bin/phpstan analyse
# Expected PHPStan Output (after correction):
# [OK] No errors found.
```








phpstan/phpstan