Style Guide Proposal: Parentheses and Braces in PHP

style-guide-proposal:-parentheses-and-braces-in-php

Objective

This document presents a thorough reflection on how to establish a readable, rigorous, and coherent coding syntax for the use of parentheses and braces in PHP. Rather than perpetuating historical conventions inherited from languages like C or Java, it is based on a clear principle: code should reflect the logic of the language, not formatting habits.

The goal of this proposal is to define a style that is:

  • Unified: one rule applies uniformly across all relevant constructs—functions, control structures, or inner expressions;
  • Systematic: each rule follows directly from syntactic structure, not from lexical category (keyword, identifier, etc.);
  • Consistent: treatment is aligned across similar cases, with no arbitrary exceptions;
  • Easy to remember: by eliminating contextual variations and aesthetic distinctions with no functional value.

We aim to define a stylistic syntax that requires no extra effort in visual classification but aligns closely with the intrinsic mechanisms of PHP.

Syntax should follow structure, not appearance

PHP has an explicit grammar where the syntactic category of each construct (function, control structure, expression) is clearly distinguishable by any developer familiar with the language. Therefore, it is unnecessary to introduce stylistic variations based solely on the lexical appearance of preceding elements.

For example:

if($x > 0) {
    ...
}
foo($x);

In the first case, if is a control structure; in the second, foo is a function. Both use parentheses to wrap an expression. Yet, common conventions (e.g., PSR-12) require a space after if but forbid a space after foo.

Why apply two different rules to the same syntactic form? This discrepancy adds no real readability. A developer can already distinguish between if and foo. Style should not compensate for distinctions that are inherently clear in the language.

Similarly, braces {} are lexical scope delimiters. Their placement should follow a consistent principle regardless of context—whether opening a function, a loop, or any other block.

The central thesis is: a shared syntactic structure should imply a shared visual representation, independent of the preceding token’s semantic role (keyword or identifier).

Inherited conventions introduce confusion

Prevalent style guides such as PSR-2 and PSR-12 inherit patterns from C-like languages. They enforce distinctions in formatting between constructs that are structurally similar. For example:

  • A function declaration must place its opening brace on the next line:
  function foo()
  {
      ...
  }
  • A control structure like if must place the brace on the same line:
  if ($x > 0) {
      ...
  }
  • A space is required after if, but forbidden after foo().

These distinctions are justified by aesthetic or historical preferences rather than grammatical necessity. They introduce a needless cognitive load, requiring developers to memorize exceptions instead of applying a predictable rule.

They also complicate the implementation of formatting tools, which must apply conditional logic rather than universal patterns. In collaborative settings, these irregularities can lead to stylistic debates or merge conflicts that are purely formal.

In the end, these conventions hinder clarity and maintainability for the sake of outdated visual expectations.

Synthesis: Toward a uniform, logical, and rule-based syntax

A better alternative is to derive style directly from the language’s actual structure. This means:

  • No space before opening parentheses, regardless of preceding token: if($x), while($y), foo($z).
  • Opening braces always on the same line as the controlling statement: function bar() {, if($x) {.
  • Closing braces alone on their own line, aligned with the block start.

This results in:

  • Simplified comprehension
  • Seamless compatibility with automated formatting tools (e.g., PHP-CS-Fixer, linters)
  • A visually clean and vertically structured codebase

The benefits are twofold:

  • For individual developers: fewer edge cases to remember, greater focus on logic
  • For teams: less friction in code reviews, clear conventions easy to share and enforce

Special case: if/elseif/else and try/catch/finally

A specific question arises regarding if/elseif/else and try/catch/finally, where it is common to begin the next block directly after a closing brace:

if($x) {
    ...
} elseif($y) {
    ...
} else {
    ...
}
try {
    ...
} catch(Exception $e) {
    ...
} finally {
    ...
}

While syntactically valid and widely accepted, these are the only cases where a new structure follows immediately after a closing brace on the same line.

Following the principle of minimizing stylistic exceptions, this behavior should be reconsidered. Specifically:

  • PHP does not require chaining these blocks on the same line.
  • Although else, catch, and finally are syntactically dependent (they cannot start independently), this does not justify a distinct visual form.
  • Maintaining vertical alignment enhances structure visibility.

Proposed rule

All blocks (if, else, elseif, try, catch, finally) must start on a new line after the previous block’s closing brace.

This ensures:

  • No stylistic exceptions
  • Clear vertical structure
  • Uniform block detection

Preferred example:

if($x) {
    ...
}
elseif($y) {
    ...
}
else {
    ...
}
try {
    ...
}
catch(Exception $e) {
    ...
}
finally {
    ...
}

This rule aligns fully with the overall goals of this guide: to reduce special cases and avoid tying formatting to specific keywords.

Modern extensions: arrow functions and ternary expressions

Some newer constructs in PHP raise stylistic questions, though they typically do not involve braces.

Arrow functions (fn)

Introduced in PHP 7.4, these use parentheses for parameters and a single expression (no braces).

Guideline:

  • No space between fn and (:

Do

  $f = fn($x) => $x + 1;

Don’t

  $f = fn ($x) => $x + 1;

Ternary expressions (? :)

These are expression-level constructs. The goal is to promote clarity:

Guidelines:

  • Use parentheses to wrap nested or complex sub-expressions.
  • Insert spaces around ? and : like any binary operator.

Examples:

$result = $x > 0 ? 'positive' : 'negative';

$message = ($x > 0)
    ? ($x > 10 ? 'large' : 'small')
    : 'zero';

These are not subject to brace-related rules and are best covered by expression formatting standards.

Conclusion

A style rule has value only if it enhances structure without interfering with it. Code should reflect program logic—not act as a canvas for visual conventions.

By choosing a unified syntax based on structural grammar, this guide offers a rational, consistent, and modern approach to writing PHP. It abandons historical formatting quirks in favor of sustainable, generalizable principles.

This is not about personal preference, but about redefining the foundations of PHP style on clear, durable, and logically grounded rules. The following sections will present each rule, its application, edge cases, and practical implications.

A Note on Perspective and Adoption

I am fully aware that proposing an alternative style guide is unlikely to change much. While this document lays out a coherent and logically structured alternative, I have little hope it will shift the current conventions in any significant way.

Most developers don’t genuinely care about syntactic consistency—as long as their code runs, builds, and passes the linter. Habits are deeply entrenched. Furthermore, the prevalence of established standards like PSR means that any deviation, however justified, is perceived as unnecessary friction.

And the arrival of AI doesn’t help. On the contrary, it reinforces the inertia. Most code generated by AI tools blindly follows existing PSR-style rules. The AI doesn’t reason about syntax—it imitates. The more these tools are used, the more the current conventions become self-reinforcing, regardless of whether they were ever truly optimal.

This guide is not an attempt to fight that tide. Rather, it is an exercise in principled reasoning. If the future of coding is to be increasingly automated, we should at least strive to encode principles that are internally consistent, teachable, and deducible—rather than inherited from historical precedent or aesthetic legacy.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
world-blood-donor-day

World Blood Donor Day

Next Post
what-the-heck-is-a-viewport?

What the Heck Is a Viewport?

Related Posts