Contents
PHP coding standards explained
Hey, fellow developers. Picture this: it's 2 AM, your screen's the only light in the room, and you're knee-deep in a legacy PHP project. Someone else's code stares back—indents all over the place, camelCase mixed with snake_case, files spitting out HTML and logic like confetti. You sigh, crack your knuckles, and think, Why does this feel like deciphering ancient runes?
I've been there. More times than I'd like. And that's exactly why PHP coding standards exist. They're not some bureaucratic checkbox. They're the quiet agreement that lets us—colleagues, freelancers, teams on Find PHP—pass code around without friction. Write once, collaborate forever.
In this piece, we'll unpack the essentials: from PSR basics to real-world habits that stick. No fluff. Just the standards that save your sanity, plus stories from the trenches. Whether you're hunting jobs, hiring talent, or just leveling up your PHP game, these rules bridge the gap between solo hacks and scalable ecosystems.
Why standards feel like home in a chaotic world
Remember your first pull request on a team project? The reviewer nitpicks tabs vs. spaces, and suddenly your brilliant algorithm feels amateur. Standards aren't about perfection. They're about predictability.
PHP's ecosystem exploded—Laravel, Symfony, WordPress—but without shared rules, it's Babel. Enter PSR (PHP Standards Recommendations), born from PHP-FIG, a group of framework authors tired of reinventing wheels. PSR-1 kicked it off with basics. PSR-2 added style. Now PSR-12 rules the roost, folding in modern PHP 7+ syntax like attributes and match expressions.
Why care? On platforms like Find PHP, you're not just coding. You're signaling: I'm reliable. My code plays nice with yours. Clean standards mean faster onboarding, fewer bugs, smoother handoffs when hiring or job-hopping.
But standards evolve. PSR-2? Deprecated since 2019. PSR-12? The current king, embraced by PhpStorm, Laravel, Symfony. Tools like PHP-CS-Fixer enforce it automatically. One composer require --dev friendsofphp/php-cs-fixer and vendor/bin/php-cs-fixer fix, and boom—your code's polished.
Have you ever refactored a 10k-line file because naming was inconsistent? Yeah. Standards prevent that heartbreak.
Breaking down PSR-1: The bare minimum
PSR-1 is your foundation. No frills, just sanity checks. Think of it as the "don't be a jerk" rule for PHP files.
- PHP tags: Stick to
<?phpor<?=. No short tags like<?or script tags. Keeps parsers happy across servers. - Naming conventions:
- Classes: UpperCamelCase (e.g.,
UserService). - Methods and properties: camelCase (e.g.,
getUserId()). - Constants: UPPER_SNAKE_CASE (e.g.,
MAX_LOGIN_ATTEMPTS).
- Classes: UpperCamelCase (e.g.,
- Files do one thing: Declare symbols (classes, functions) or cause side effects (output, ini tweaks). Not both. Auto-loading a file mid-script? Side effect. Bootstraps hate that.
- Encoding: UTF-8 without BOM. No invisible gremlins corrupting your strings.
- Namespaces: Follow PSR-4 for autoloading magic.
Example time. Bad:
<?
class user_service {
const max_attempts=5;
function getUser(){}
echo "Hello"; // side effect!
}
Good:
<?php
namespace App\Services;
class UserService
{
public const MAX_ATTEMPTS = 5;
public function getUser(): User
{
// Pure logic here
}
}
That shift? Night and day. I once inherited a project ignoring PSR-1. Classes named userService, constants in lowercase. Two days lost to IDE confusion. Lesson learned.
PSR-12: The full style symphony
PSR-12 builds on PSR-1, adding rhythm. It's for PHP 7+, handling arrow functions, attributes, heredocs. Deprecated PSR-2 lives on in legacy code, but migrate now.
Key beats:
- Indentation: 4 spaces. Tabs? Exile. Your editor's job.
- Line length: Soft limit 120 chars, ideal under 80. Wrap smartly—no mid-expression breaks unless needed.
- Blank lines: One after
namespace, one afteruseblocks. Classes start fresh. - Braces: Same line for classes/methods:
class Foo {. Control structures (if, for) on next line. - Keywords: Lowercase (
true,false,null). PHP constants too. - File endings: Unix LF. End with a blank line. Omit closing
?>in pure PHP files—avoids leaks. - Visibility:
public,protected,privatebeforestaticorfinal. Order: visibility first.
Modern twist: Arrow functions shine here. PHP 7.4+ lets you write fn($x) => $x * 2 cleanly—no import hassles.
Real code snippet, PSR-12 compliant:
<?php
declare(strict_types=1);
namespace App\Services;
use App\Models\User;
class UserService
{
public function findActiveUsers(): array
{
return User::query()
->where('active', true)
->get()
->map(fn(User $user) => $user->toArray())
->toArray();
}
}
See the flow? Readable at a glance. I refactored a Laravel API like this last month—deploy time dropped, juniors onboarded in hours.
Beyond PSR: Habits that make you unstoppable
Standards are table stakes. True mastery? Layer on best practices. These aren't in every PSR, but they're ecosystem gospel.
Encoding and strings: UTF-8 or bust
PHP defaults can bite. Always mb_internal_encoding('UTF-8'); mb_http_output('UTF-8'); at script top. Use mb_* functions: mb_strlen, mb_substr. Forget once? Garbled emojis, broken international sites. I've seen production crashes from strlen on accented names. Painful.
For htmlentities or htmlspecialchars, specify UTF-8. PHP 5.4+ defaults it, but explicit is kind.
Namespaces and autoloading: PSR-4 magic
Ditch require hell. PSR-4 maps namespaces to directories: App\Models\User loads from app/Models/User.php. Composer handles it. Collision-free, scalable.
DRY, loops, and performance tweaks
- Meaningful names:
$usersover$data. Self-documenting. - No functions in loops:
for ($i = 0; $i < count($array); $i++)callscountevery iteration. Cache it:$count = count($array);. - Arrow functions: One-liners without boilerplate.
- IDE power: PhpStorm auto-fixes PSR-12, suggests refactors. Pair with PHPStan for static analysis.
In a recent gig, we enforced this via composer scripts:
{
"scripts": {
"cs-fix": "vendor/bin/php-cs-fixer fix",
"stan": "vendor/bin/phpstan analyse"
}
}
Pre-commit hook. Zero debates.
Frameworks and tools: Laravel, Symfony love standards
WordPress has its own (PEAR-inspired), but PSR-12 wins for new projects. Laravel's artisan enforces it. Symfony too. Hiring? Check their GitHub—PSR compliance screams pro.
Tools to enforce it all
Don't rely on willpower. Automate:
- PHP-CS-Fixer:
php-cs-fixer fix src/ --rules=@PSR12. - PHPStan: Catches type issues early.
- EditorConfig:
.editorconfigfor team-wide indents. - Prettier/PHP plugins: VS Code, PhpStorm.
Surveys show teams using these ship 30% faster. I've lived it—legacy cleanup became joy.
The human side: Standards as trust
Late nights debugging? Standards cut that time in half. But more: they build bridges. On Find PHP, your resume shines if your repos follow PSR. Hiring? Spot clean code, hire confidently.
I once paired with a dev whose code felt like poetry—PSR-12, typed, documented. We shipped features in days. Contrast: messy code, weeks of arguments.
What if standards were muscle memory? You'd code faster, think deeper. Tools exist. Habits form.
Wrapping the philosophy
Standards aren't chains. They're wings. They free you to innovate atop solid ground.
Next project, run php-cs-fixer. Feel the shift. That quiet confidence when code just works with anyone else's? Priceless.
And in those glowing-monitor moments, you'll code not just correctly, but humanly. Leaving a trail others can follow, build on, call home.