Best PHP code style for WordPress developers?

PHP-8.2-whats-new

Code style has always been a topic of huge debate since programming was a thing. One of the more famous and debated questions, namely the usage of tabs or spaces for code indentation, has even been mentioned in the popular TV series Silicon Valley.

To provide some more concrete evidence towards the discussion, StackOverflow has conducted a survey, in which the income of developers who use tabs versus those who use spaces was compared. In this almost ridiculous “holy war” for the best code style, we try to provide our own voice on the best PHP code style for WordPress plugin and theme developers.

As the WordPress core backend is written in PHP, it would definitely make sense to follow the WordPress PHP coding standards when developing plugins or themes for WordPress. Although we mostly follow those standards in our own WordPress-related development, there are some peculiarities in the WordPress coding standards that in our opinion are not very reasonable to follow.

In this article, we will provide our own exceptions to the WordPress PHP coding standards and try our best to convince you to also use them.

Indentation Using Two Spaces

For indentation, we prefer to use two (2) spaces instead of the tabs recommended by WordPress:

if ( $something ) {
  $some_variable = 'something';
}

Using spaces ensures that the code is displayed the same way in all editors, and by using only two spaces the indentation is comfortable for multiple indentation levels so that the code indentation does not reach too far right. This issue is especially evident in template files that contain HTML markup inside PHP code files or other code with multiple indentation levels.

Indenting multiple consecutive assignments or associative array to the same level is not necessary:

// INCORRECT ✘
$foo   = 'somevalue';
$foo2  = 'somevalue2';
$foo34 = 'somevalue3';
$foo5  = 'somevalue4';
$foo6  = array(
  'foo1'         => 'bar1',
  'foo223'       => 'bar2',
  'foo123456789' => 'bar3',
);

// CORRECT ✔
$foo = 'somevalue';
$foo2 = 'somevalue2';
$foo34 = 'somevalue3';
$foo5 = 'somevalue4';
$foo6 = array(
  'foo1' => 'bar1',
  'foo223' => 'bar2',
  'foo123456789' => 'bar3',
);

Having so many spaces causes unnecessary overhead when having to update existing code; if a variable with a longer name were to be added into the block, the indentation of all the other variables would have to be updated, too, which in our opinion makes no sense. Adding a patch to your codebase should not require also changing the style of already existing code around it.

Adding a patch to your codebase should not require changing the style of already existing code around it.

Don’t Overdo it With Whitespace

Excessive usage of horizontal whitespace everywhere should not be necessary, even though it is required by the WordPress PHP Coding Standards for rendering the code more readable. However, the argument for better readability is rather subjective and highly debatable, as the code style guidelines of most programming languages and frameworks usually advice to do the very contrary: to use horizontal whitespace quite sparingly. For instance, PSR-2 for PHP, PEP8 for Python and the Google JavaScript Style Guide only allow horizontal whitespace in very specific locations.

We prefer to lean a bit more towards the WordPress Coding Standards on this topic, instead of completely refusing to use whitespace. Horizontal whitespace should indeed be used, but only in specific locations in order to add a certain emphasis instead of going to extremes and flooding the code with whitespace everywhere.

Firstly, it is advisable to use space after the opening and before the closing parentheses of if, elseif, foreach, for and switch control structures:

foreach ( $items as $item ) {
  if ( $item['type'] === 'book' ) {
    read($item);
  } elseif ( $item['type'] === 'food' ) {
    if ( is_delicious($item) ) {
      eat($item);
    } else {
      throw_away($item);
    }
  } else {
    ...

The reason for this is because this separates the structures better from the appearance of function calls and makes the conditions clearer, which results in the code being more readable.

A single space should also be used after the opening and before the closing parentheses of a function declaration, for improved readability:

function some_function( $param1, $param2 = 'something' ) {
  …

However, there is no need to add whitespace around parentheses in other situations, like when calling functions:

// INCORRECT ✘
if ( $b || ( $b && $c ) ) {
  do_something( $a, callback( $b, $c ) );
}

// CORRECT ✔
if ( $b || ($b && $c) ) {
  do_something($a, callback($b, $c));
}

There is also no need to add space around array indices even if they are variables:

// INCORRECT ✘
$value = $foo[ $bar ];

// CORRECT ✔
$value = $foo[$bar];

Use Yoda Conditions, You Must Not

The WordPress PHP coding standards recommend using Yoda conditions, in which the assigned value should come before the variable. The reason for using them is to catch bugs that would be caused by simply using a single equal mark for assignment, because you can not assign a value to a value, like true = $foo or 'somevalue' = $foo.

In our experience this makes the code much harder and slower to read. The bugs that you might catch this way will be found with a proper code static analysis that restricts assignments to always be the first item on a code row. As such, Yoda conditions should be avoided:

// INCORRECT ✘
if ( 'somevalue' === $something ) {
  ...
}

// CORRECT ✔
if ( $something === 'somevalue' ) {
  ...

Automating Static Code Analysis

Code style is often just a personal preference and there is no way of objectively defining which code style is correct. However, the code style inside a codebase should be unified. All developers working on the same codebase should use the same code style. For that reason, it makes sense to somehow automatically validate that the style of the code the developer is producing matches the unified style. This is usually done in the form of static code analysis, where the application source files are read in text form without actually executing the program.

Code style is often just a personal preference and there is no way of objectively defining which code style is correct.

For running the static code analysis, we use PHP CodeSniffer (PHPCS), which has a WordPress Coding Standards ruleset available. It is also possible to define custom rulesets with a configuration file. For example, in the GitHub repository of our own open-source WordPress plugin Seravo Plugin we have a custom phpcs.xml configuration file that defines the WordPress-Extra ruleset as a base and then adds some exceptions to the rules. We have also written a separate blog article about PHP CodeSniffer, which will explain its usage more thoroughly.

If you happen to use GitHub as your Git service provider, static code analysis can be easily run for Git commits automatically by adding a Continuous Integration (CI) tool like Travis CI into your GitHub repository.

What do you think is the best PHP coding style? We’d love to hear your opinion, so please feel free to comment below. Based on the discussion, we will add a base ruleset into our WordPress project template.