PHP Techniques to Write Clean and Readable Code
Tags: wordpress
Published: 2020-11-10 02:23:43

When starting a project, developers should think about how to <strong>write clean and readable PHP code</strong> so that it can be <strong>easy to maintain and fix when there's a bug</strong>. To meet these requirements, developers in the team should follow <strong>coding standards and best practices</strong>.

<!--more-->

What are these coding standards and best practices? Are there any <strong>PHP techniques to write clean and readable code</strong>? The answers can be found right in this article!

<img class="aligncenter" src="https://i.imgur.com/mpdJBGF.jpg" alt="Write clean and readable code following PHP techniques" width="5184" height="3456" />

<h2>What are the Coding Standards?</h2>

Coding standards are the rules for coding that are set up by developers in a project. When every project member follows these coding standards, the code can be easy to read, reuse, and improve.

These are the benefits of the coding standards:

<ul>

   <li>The coding standards play an important role as the blueprint for all the project members. That helps everyone to understand each other's code more easily.</li>

   <li>With the appropriate way of coding, your code will become simpler and cleaner, helping you avoid common mistakes.</li>

   <li>When you want to copy the code to use for other projects, you can easily do so without reducing the code quality.</li>

</ul>

The coding standards consist of these following common elements:

<ul>

   <li>Naming variables, constants, functions, classes, ...</li>

   <li>Using spaces or tabs</li>

   <li>Declaring and using variables</li>

   <li>Comment</li>

   <li>The maximum length for a line of code, file, ...</li>

</ul>

In case you're developing products for WordPress like themes and plugins, you have to follow the <a href="https://make.wordpress.org/core/handbook/best-practices/coding-standards/php/">WordPress coding standards</a>. However, these coding standards have some strict rules that I think you may not need to follow. And here are the main rules in the WordPress coding standards that you should comply with:

<h3>Indentation and Line Length of Code</h3>

You should use tabs instead of spaces to help computers display the code in the most flexible way. In terms of line length, a line of code should be in 75 - 85 characters to make the code more readable.

<h3>Declare Arrays</h3>

WordPress requires developers to declare long array syntax (1, 2, 3). However, from the 5.4 version, PHP supports writing short array syntax [1, 2, 3]. And it's totally fine to use short array syntax. In fact, it's encouraged to do so.

<h3>Shorthand PHP Tag</h3>

WordPress requires you to write the full PHP tag as follows:

<pre>&lt;?php echo 'Some text'; ?&gt;</pre>

But from the 5.4 version, PHP supports writing short tags (this feature is always on), so you can use it for a cleaner command:

<pre>&lt;?= 'Some text'; ?&gt;</pre>

<h3>Control Structure</h3>

Control structure includes <code>if</code>, <code>for</code>, <code>while</code>, <code>switch</code>, ... Between these words and the opening bracket, you should use <strong>ONE space</strong> (press the spacebar <strong>only ONCE</strong>) to distinguish them from function calls.

<pre><span style="font-weight: 400;">if ( ( condition 1 ) || ( condition 2 ) ) { </span>

<span style="font-weight: 400;">    the action to be implemented 1; </span>

<span style="font-weight: 400;">} elseif ( ( condition 3 ) &amp;&amp; ( condition 4 ) ) { </span>

<span style="font-weight: 400;">    the action to be implemented 2; </span>

<span style="font-weight: 400;">} else { </span>

<span style="font-weight: 400;">    the action to be implemented by default; </span>

<span style="font-weight: 400;">}</span></pre>

As for switch commands, you can code as follows:

<pre><span style="font-weight: 400;">switch ( condition ) {</span>

<span style="font-weight: 400;">    case 1:</span>

<span style="font-weight: 400;">        the action to be implemented</span>

<span style="font-weight: 400;">        break;</span>

<span style="font-weight: 400;">    case 2:</span>

<span style="font-weight: 400;">        the action to be implemented</span>

<span style="font-weight: 400;">        break;</span>

<span style="font-weight: 400;">    default:</span>

<span style="font-weight: 400;">        the default action</span>

<span style="font-weight: 400;">        break;</span>

<span style="font-weight: 400;">}</span></pre>

<h3>Function Calls</h3>

When calling a function, you should add <strong>ONE space</strong> between the function name, the opening parenthesis, and the first variable, don't write it without spaces. You should also add a space between the comma and each parameter, between the last parameter, the closing bracket, and the semicolon. For better visualization, see the below example of a function call coding standards:

<pre>$var = foo( $bar, $baz, $quux );</pre>

<h3>Naming Files and Classes</h3>

In WordPress, all classes must be named <code>Class_Name</code>. You need to capitalize the first letter of each word and separate it with an underscore.

The filename of the class is written as <code>class-class-name.php</code>. You have to add the <code>class-</code> prefix, lowercase class names, and separate words with dashes.

However, when working with "big" plugins and themes, you should use Composer to automatically load files. In this case, the coding standards above can't work anymore because Composer follows PSR's rules. Therefore, it's crucial to follow the PSR files and classes naming rules if you use Composer:

<ul>

   <li><strong>Class name</strong>: in the form of <code>ClassName</code> (capitalize the first letter of each word and write the words without spaces).</li>

   <li><strong>Filename</strong>: in the form of <code>ClassName.php</code> (the file's name is the same as the class's name).</li>

</ul>

In addition, these files are placed in the folders that correspond to their namespaces. For example, a class with the full name of <code>\ALSearch\Shortcode\Field</code> will be placed in the <code>src\ShortCode</code> folder, and its file's name is <code>Field.php</code>. In this example, the src folder corresponds to the <code>ALSearch</code> namespace, while other parts of the class name correspond to the parts that are in the same hierarchy.

<h3>Yoda Condition</h3>

In case the logical comparisons have variables, you should place constants, literals, and function calls on the left, and put variables on the right.

<pre><span style="font-weight: 400;">if ( true === $the_force ) {</span>

<span style="font-weight: 400;">    $victorious = you_will( $be );</span>

<span style="font-weight: 400;">}</span></pre>

The purpose of this coding style is to ensure the data type (because of the typecasting when comparing PHP) and avoid errors when you write <code>=</code> instead of <code>==</code>. However, it has a downside, which makes your code more difficult to read and understand, especially for new coders.

<h3>The <code>?:</code> Operator</h3>

WordPress doesn't allow using the <code>?:</code> operator in the short form. It always requires writing in the long form:

<pre>$type = $type ? $type : 'select';</pre>

However, from version 5.3, you can write it shorter to make them easier to read as follows:

<pre>$type = $type ?: 'select';</pre>

<h2>PHP Best Practices</h2>

There are several coding techniques that we use in our projects to make the code more optimal and easier to read and fix. I have summarized those techniques in the following sections:

<h3>Consistency</h3>

You should code in the same style for a function, class, or file, and avoid coding in different styles for the same code like the following example:

<pre><span style="font-weight: 400;">&lt;?php if ( $args['label'] ) : ?&gt;</span>

<span style="font-weight: 400;">    &lt;span class="als-field__label"&gt;&lt;?php echo esc_html( $args['label'] ); ?&gt;&lt;/span&gt;</span>

<span style="font-weight: 400;">&lt;?php endif; ?&gt;</span>

<span style="font-weight: 400;">&lt;?php</span>

<span style="font-weight: 400;">if ( $args['prefix'] ) {</span>

<span style="font-weight: 400;">    echo '&lt;span class="als-field__prefix"&gt;' . esc_html( $args['prefix'] ) . '&lt;/span&gt;';</span>

<span style="font-weight: 400;">}</span></pre>

The above code displays the label and the prefix. Although the coding styles are different, they return the same result. Therefore, we should rewrite them consistently as follows:

<pre><span style="font-weight: 400;">if ( $args['label'] ) {</span>

<span style="font-weight: 400;">    echo '&lt;span class="als-field__label"&gt;', esc_html( $args['label'] ), '&lt;/span&gt;';</span>

<span style="font-weight: 400;">}</span>

<span style="font-weight: 400;">if ( $args['prefix'] ) {</span>

<span style="font-weight: 400;">    echo '&lt;span class="als-field__prefix"&gt;', esc_html( $args['prefix'] ), '&lt;/span&gt;';</span>

<span style="font-weight: 400;">}</span></pre>

<h3>Early Return</h3>

If the conditional blocks are too large, the code will be very difficult to read and you will find it harder to follow the logic. To fix this, you need to write small conditional blocks. One of the techniques to do it is "early return" - return as soon as possible.

For instance, I have the following code that hasn't been optimized:

<pre>if ( 'none' !== $field['sanitize_callback'] ) {

    if ( is_callable( $field['sanitize_callback'] ) {

        $value = call_user_func( $field['sanitize_callback'], $value, $args );

    } else {

        // a very long code

    }

}

return $value;

</pre>

When you apply the "early return" technique, this code is rewritten as follows:

<pre>if ( 'none' === $field['sanitize_callback'] ) {

    return $value;

}

if ( is_callable( $field['sanitize_callback'] ) {

    return call_user_func( $field['sanitize_callback'], $value, $args );

}

// a very long code.

return $value;

</pre>

<h3>Set the Default Value</h3>

Setting the default value helps us remove conditional statements that check the existence of that value, thus making your code simpler and more readable.

Below is the code that hasn't been optimized:

<pre>if ( isset( $args['prefix'] ) &amp;&amp; $args['prefix'] !== '' ) {

    echo '<span class="als-field__prefix">', esc_html( $args['prefix'] ), '</span>';

}

if ( isset( $args['label'] ) &amp;&amp; $args['label'] !== '' ) {

    echo '<span class="als-field__label">', esc_html( $args['label'] ), '</span>';

}

</pre>

After setting the default value, the code becomes more readable:

<pre>$args = wp_parse_args( $args, [

    'prefix' =&gt; '',

    'label' =&gt; '',

] );

if ( $args['prefix'] ) {

    echo '<span class="als-field__prefix">', esc_html( $args['prefix'] ), '</span>';

}

if ( $args['label'] ) {

    echo '<span class="als-field__label">', esc_html( $args['label'] ), '</span>';

}

</pre>

<h3>Output Multiple Values with echo</h3>

When we need to output a lot of texts, we usually code like this:

<pre>echo '&lt;span class="als-field__prefix"&gt;' . esc_html( $args['prefix'] ) . '&lt;/span&gt;';</pre>

However, this approach isn't as optimal as using the <code>echo</code> function. The <code>echo</code> function allows us to pass many parameters at once, so it works faster than the normal function:

<pre>echo '&lt;span class="als-field__prefix"&gt;', esc_html( $args['prefix'] ), '&lt;/span&gt;';</pre>

<h3>Use Lazy Declaration and Declare Only When Necessary</h3>

Remember that you should only declare variables when needed. This declaration also includes creating the initial value.

In addition, you should declare as late as possible. Better yet, you should declare right on the code that uses that variable.

Below is an example of the unnecessary variable declaration:

<pre>$date = parent::get_date();

$format = ''; // Declare unnecessarily because this variable is declared again in the below code

if ( $meta ) {

    $format = 'Y-m-d';

    return date( $format, $date );

}

</pre>

You should declare the variable as follows:

<pre>$date = parent::get_date();

if ( $meta ) {

    $format = 'Y-m-d';

    return date( $format, $date );

}

</pre>

Here is an example of declaring variables too early when we haven't used them yet:

<pre>$format = 'Y-m-d';

// A very long code.

return date( $format, $date );

</pre>

You should only declare the <code>$format</code> variable right before the code that uses it as follows:

<pre>// A very long code.

$format = 'Y-m-d';

return date( $format, $date );

</pre>

<h2>Last Words</h2>

Improving and optimizing code is always a matter of concern for coders. The cleaner and more readable your code is, the more efficient your teamwork is. Besides, it will be easier to handle when there's an issue. Therefore, don't forget to apply the above techniques to get the best results.

If there are any other useful tips for coding, feel free to share it with us in the comment section!
--- --- ---

The publication at [Meta Box](https://metabox.io/php-technique-write-clean-readable-code/).