| title | PHP Coding Style |
|---|---|
| scope | php |
Follow PSR-12 and PER Coding Style 2.0 as the baseline. Key rules:
- Start every PHP file with
<?php(no closing tag) - Declare
declare(strict_types=1);in every file - One class/interface/trait/enum per file
- Follow PSR-4 autoloading: namespace maps to directory structure
- Classes, interfaces, traits, enums:
PascalCase - Methods, functions, variables:
camelCase - Constants:
UPPER_SNAKE_CASE - Namespaces:
PascalCase, matching directory structure
- Always declare parameter types, return types, and property types
- Use union types (
string|int) instead of docblock@param string|int - Use
mixedexplicitly when the type is truly unknown - Use
voidreturn type for methods that return nothing - Prefer
readonlyproperties over getters for value objects - Use constructor promotion for simple DTOs and value objects
- Use
enuminstead of class constants for fixed sets of values - Use
readonlyproperties for immutable data - Use
matchinstead ofswitchwhen returning values - Use named arguments for clarity when calling functions with many parameters
- Use first-class callable syntax
strlen(...)instead of'strlen'strings - Use null-safe operator
?->instead of nested null checks - Use fiber-based async when appropriate
- Prefer
finalclasses by default — only removefinalwhen extension is explicitly needed - Prefer composition over inheritance
- Keep classes small and focused (Single Responsibility)
- Use interfaces for contracts, abstract classes only when sharing implementation
- 4 spaces indentation (no tabs)
- Opening braces on the same line for control structures
- Opening braces on the next line for classes and methods
- One blank line between methods
- No trailing whitespace
- Single blank line at end of file
- Use PHP-CS-Fixer or Laravel Pint for automated formatting
- Configure rules to match PSR-12/PER-CS
- Run formatter on save or pre-commit