Yoda Conditions
debt(d3/e1/b3/t5)
Closest to 'default linter catches the common case' (d3). The detection_hints list phpcs and php-cs-fixer, both standard linters that flag Yoda conditions automatically with default or near-default rulesets. The code_pattern is explicit and mechanical, making automated detection straightforward.
Closest to 'one-line patch or single-call swap' (e1). The quick_fix is a direct mechanical swap — reorder the operands from '42 === $age' to '$age === 42'. php-cs-fixer can automate this across a codebase in one pass. No logic changes required.
Closest to 'localised tax' (b3). The burden is a consistency/readability tax felt across any file using the inconsistent style, but it doesn't affect architecture or cross-cutting concerns. The common_mistakes note that inconsistency is the real problem — a team that agrees on one style pays minimal ongoing cost.
Closest to 'notable trap' (t5). The misconception field states that developers believe Yoda conditions are 'always safer' when in fact modern PHP (strict_types, PHP 8 match, phpstan) eliminates the original safety benefit. The 'obvious' reason to use Yoda conditions (preventing accidental assignment) no longer holds for most modern PHP code, and PSR-12 actively discourages it — a documented gotcha that experienced PHP developers eventually learn.
Also Known As
TL;DR
Explanation
Yoda conditions (if (42 === $answer)) put the constant on the left side of a comparison so that accidentally writing = instead of == causes a parse error (constants are not assignable). They were a popular PHP defensive style to prevent the common bug of writing if ($x = 5) instead of if ($x == 5). Modern IDEs, static analysers (PHPStan, Psalm), and strict_types make Yoda conditions unnecessary. PSR-12 does not mandate them. Most modern PHP style guides actively discourage Yoda conditions as they reduce readability.
Common Misconception
Why It Matters
Common Mistakes
- Using Yoda conditions for comparisons between two variables — $a === $b is the same either way.
- Inconsistent use — some files use Yoda, others don't, creating cognitive overhead.
- Relying on Yoda conditions as the sole defence against assignment bugs — use strict_types and linters instead.
- Not following the project's agreed convention — either style is fine; inconsistency is the problem.
Code Examples
// Yoda condition — value on left
if ('admin' === $role) {}
if (null === $user) {}
// Normal order — subject on left, more readable:
if ($role === 'admin') {}
if ($user === null) {}
// PHP 8+ strict_types makes assignment-in-condition errors a type error:
// declare(strict_types=1);
// if ($user = getUser()) {} // works, but consider using ??=
// PSR-12 doesn't mandate either style — pick one and be consistent
// phpcs.xml rule to enforce style:
// <rule ref="Generic.ControlStructures.DisallowYodaConditions"/>