Style rules sound dull, but they decide how easily your code can be read, shared and reviewed. PHP has a widely accepted standard: PSR-12, from the PHP-FIG group.
The main rules
- Files use
<?phpand no closing tag (pure PHP files). - Use 4 spaces to indent, not tabs.
- One class per file, and the file name equals the class name.
- Class names in PascalCase, methods and variables in camelCase, constants in UPPER_SNAKE_CASE.
- Opening braces: on a new line for classes and methods, on the same line for
if, loops and closures. - A blank line after the namespace and after the
useblock. - Keep lines reasonably short (about 80 to 120 characters).
- Add
declare(strict_types=1);after the opening tag.
A well-formatted file
<?php
declare(strict_types=1);
namespace App\Service;
use InvalidArgumentException;
final class PriceCalculator
{
private const TAX_RATE = 0.18;
public function __construct(private readonly string $currency = "INR")
{
}
public function withTax(float $price): float
{
if ($price < 0) {
throw new InvalidArgumentException("Price cannot be negative.");
}
return round($price * (1 + self::TAX_RATE), 2);
}
}
echo (new PriceCalculator())->withTax(100);
118
Naming
| Thing | Style | Example |
|---|---|---|
| Class, interface, trait, enum | PascalCase | UserRepository |
| Method, function | camelCase | findByEmail() |
| Variable, property | camelCase | $orderTotal |
| Constant | UPPER_SNAKE | MAX_RETRIES |
| Namespace | PascalCase | App\Http\Controllers |
Name things for what they are, not how they work. $users is better than $arr, and calculateTotal() is better than doStuff().
Booleans and methods
Start boolean-returning methods with is, has, can or should: isActive(), hasPermission().
Comments and docblocks
- Write a comment to explain why, not what.
- If a type is clear from the code, you do not need a docblock. Use docblocks for things the type system cannot say, such as
@param string[] $tagsor@throws.
Tools that enforce style
You do not need to remember the rules. Tools check and fix them.
| Tool | What it does |
|---|---|
PHP_CodeSniffer (phpcs, phpcbf) | Checks and fixes code against a standard such as PSR-12 |
| PHP CS Fixer | Rewrites code to match a style |
| Laravel Pint | A ready-made fixer based on PHP CS Fixer |
| PHPStan / Psalm | Static analysis: finds type and logic mistakes |
| Editor formatting | VS Code and PhpStorm can format on save |
Install them with Composer (see What Is Composer?):
composer require --dev squizlabs/php_codesniffer
vendor/bin/phpcs --standard=PSR12 src/
Consistency beats perfection
If a project already has a style, follow it, even if you would choose differently. A file that matches the rest of the project is easier to read than one that is “better” but different.
The WordPress exception
WordPress has its own coding standards (tabs, snake_case function names, spaces inside brackets). When you write code for a WordPress theme or plugin, follow the WordPress standard. For everything else, use PSR-12.