PHP - Static Code Analysis in PHP (PHPStan and Psalm)

Static code analysis is the process of examining source code without actually executing it. In PHP, static analysis tools such as PHPStan and Psalm are widely used to detect bugs, enforce coding standards, and improve overall code quality during development.


What is Static Code Analysis

Static analysis works by parsing your code and analyzing its structure, types, and logic to identify potential issues. Unlike runtime debugging, it helps catch errors early in the development process before the code is even executed.

These tools simulate how the code behaves and check for inconsistencies such as incorrect types, undefined variables, or unreachable code.


Why Static Analysis is Important

PHP is a dynamically typed language, which means type-related errors may not appear until runtime. Static analysis tools introduce a level of strictness by checking types and logic beforehand.

Key benefits include:

  • Early detection of bugs

  • Improved code reliability

  • Better adherence to coding standards

  • Easier refactoring of large codebases

  • Increased developer confidence


PHPStan Overview

PHPStan is a popular static analysis tool focused on finding bugs without requiring code execution.

Key Features

  • Detects undefined variables and methods

  • Identifies incorrect method calls

  • Checks type compatibility

  • Supports different strictness levels (Level 0 to Level 9)

  • Integrates with modern PHP features

Example

function add(int $a, int $b): int {
    return $a + $b;
}

echo add(5, "10");

PHPStan will flag an error because a string is passed instead of an integer.


Psalm Overview

Psalm is another advanced static analysis tool with strong type inference and security analysis capabilities.

Key Features

  • Advanced type inference

  • Taint analysis for security vulnerabilities

  • Supports annotations (docblocks)

  • Detects unused code

  • Provides automatic fixes in some cases

Example

Psalm can detect issues like passing null to a non-nullable parameter or accessing undefined array keys.


How Static Analysis Works

Both tools follow a similar process:

  1. Parse PHP files into an abstract syntax tree (AST)

  2. Analyze function and method signatures

  3. Track variable types across the codebase

  4. Identify inconsistencies and potential errors

  5. Generate reports with warnings and errors


Type Checking and Inference

Static analyzers can understand types even when they are not explicitly declared.

Example:

$user = getUser();
echo $user->name;

If getUser() is known to return a User object, the tool validates access to the name property. If the type is uncertain, it will raise a warning.


Configuration and Levels

PHPStan Levels

PHPStan allows you to increase strictness gradually:

  • Lower levels detect basic issues

  • Higher levels enforce strict typing and deeper checks

This helps teams adopt static analysis incrementally.


Psalm Configuration

Psalm uses configuration files to define:

  • Error reporting levels

  • Project structure

  • Type annotations

It can also enforce strict typing rules across the codebase.


Integration with Development Workflow

Static analysis tools are commonly integrated into:

  • IDEs for real-time feedback

  • Continuous Integration pipelines

  • Pre-commit hooks

This ensures code quality is maintained consistently across teams.


Static Analysis vs Runtime Testing

Static analysis and testing serve different purposes:

  • Static analysis detects potential issues without running code

  • Testing verifies actual behavior during execution

Both should be used together for maximum reliability.


Limitations

While powerful, static analysis has some limitations:

  • May produce false positives

  • Requires configuration and learning

  • Cannot detect runtime-specific issues

  • Complex dynamic code may be harder to analyze


Best Practices

  • Start with a lower strictness level and gradually increase

  • Add type hints wherever possible

  • Use docblocks for better type clarity

  • Fix errors regularly instead of ignoring them

  • Combine with unit testing for complete coverage


Conclusion

Static code analysis in PHP using tools like PHPStan and Psalm plays a crucial role in modern development. It helps identify errors early, enforce type safety, and maintain high-quality code. By integrating these tools into the development workflow, developers can build more robust and maintainable applications while reducing the risk of bugs and unexpected behavior.