PHP Coding Standards with Best Example

Based on the standard practices of every programmer, each organization has its own coding standards.

PHP Coding Standards are important because there may be many programmers working on different modules.

If each of them made their own coding standards, the source code would become very hard to manage, which would make it impossible to fix in the future.

Reason to maintain the coding standards:

  • Because of their familiarity, people working in different modules can easily handle the source code.
  • It serves as a model for other team members to learn the code for management or adjustments.
  • Because it is simple to understand, simplicity saves a lot of time when making common mistakes.
  • Coding standards or industry standards increase software quality and consistency.

The following are a few recommendations to follow in order to maintain the standard of PHP coding.

Opening and Closing PHP Tags

To separate PHP code, you must use the standard PHP tags instead of the shorthand tags.

This is required by PHP and is also the easiest way to include PHP code on different operating systems and in different ways.

Standard PHP Tag:

<php
    //php code here
?>

Shorthand PHP Tag:

<?
    //php code here
?>

Single and Double Quotes

When appropriate, use single and double quotation marks. If you are not evaluating any of the string’s contents, use single quotes.

You should almost never need to escape quotes within a string, as you may just alternate your quoting style:

<?php
    // this is an example using a single quotation marks
    echo '<a href="#" class="button">This is using Single Quotes</a>';
    echo '<br>';
    // this is an example using double quotation marks
    echo "<a href='{$escaped_link}'>This is using Double Quotes</a>";

    // the incorrect way
    echo "<a href="#" class="button">This is using Single Quotes</a>";
    echo '<a href='{$escaped_link}'>This is using Double Quotes</a>';
?>

Writing include/require statements

Since include[_once] and require[_once] are language constructs, they do not require parentheses around the path; therefore, they should not be used.

Only one space should exist between the path and the include/require keywords.

It is strongly advised that require[_once] unconditional includes be used. When using include[_once], PHP will throw a warning when the file is not found but will continue execution.

If your application depends on the file being loaded, this will probably cause other errors, warnings, or notices to be thrown, which could leave security holes.

Therefore, require[_once] is the preferred option, as it throws a Fatal Error if the file cannot be located.

<?php
    // This is the correct way
    require_once 'header.php';

    // The Incorrect way of writing include and require statements
    include_once  ( 'file-name.php' );
    require_once     __DIR__ . '/file-name.php';
?>

Naming Conventions

Use lowercase letters for naming variables, actions, and functions (never camelCase). Separate each word with underscores.

Do not abbreviate variable names excessively; the code should be self-documenting and straightforward.

<?php
    // Do this
    function some_name( $some_variable ) {}

    // Don't do this
    function someName( $variableName ) {}
?>

Class, trait, interface, and enum names should use capitalized and underscore-separated terms. All acronyms should be capitalized.

<?php
    class Walker_Category extends Walker {}
    class WP_HTTP {}

    interface Mailer_Interface {}
    trait Forbid_Dynamic_Properties {}
    enum Post_Status {}
?>

Constants should be capitalized with underscores between each word.

<?php
    define( 'PI_VALUE', true );
?>

The names of files should be descriptive and all lowercase. Words should be separated by hyphens.

<?php
    require 'my-plugin-name.php';
?>

Space Usage

After commas and between logical, arithmetic, comparison, string, and assignment operators, always use spaces.

<?php
    SOME_CONST === 50;
    foo() && bar();
    ! $bar;
    array( 7, 3, 5 );
    $baz . '-5';
    $term .= 'X';
    if ( $object instanceof Post_Type_Interface ) {}
    $result = 3 ** 3; // 27
?>

Put spaces around the control structure parenthesis.

<?php
    foreach ( $foo as $bar ) {
        ...
    }
?>

Defining a function:

<?php
    function my_function( $param1 = 'sample', $param2 = 'text' ) { ...

    function my_other_function() { ...
?>

Calling a function:

<?php
    sample_function( $param1, func_param( $param2 ) );
    sample_function2();
?>

Performing Logical Comparisons:

<?php
    if ( ! $sample ) { ... }
?>

Always use the abbreviated form of Typecasts, (int) rather than (integer) and (bool) rather than (boolean), and write it with lowercase letters.

However, for float casting, use (float), not (float) (real). This function is deprecated in PHP 7.4 and eliminated in PHP 8.

<?php
    foreach ( (array) $sample as $sample2 ) {
    ...
    $sample = (bool) $sample2;
?>

In certain cases, while discussing array items, you should only place a space around the index if it is a variable, as seen below.

<?php
    $z = $x['y']; // Correct.
    $z = $x[ 'y' ]; // Incorrect.

    $z = $x[0]; // Correct.
    $z = $x[ 0 ]; // Incorrect.

    $z = $x[ $y ]; // Correct.
    $z = $x[$y]; // Incorrect.
?>

In a switch block, however, there should be no spaces between the case condition and the colon.

<?php
    switch ( $x ) {
    case 'yyy': // Correct.
    case 'yy' : // Incorrect.
}
?>

Likewise, return-type declarations should not have a space before the colon.

<?php
    function sum( $x, $y ): int {
    return $x + $y;
    }
?>

Except as explicitly indicated, parentheses should contain spaces.

<?php
    if ( $a && ( $b || $c ) ) { ...

    sample_function( ( $x - 1 ) * 5, $y );
?>

When employing these operators, there should be no space between the increment (++) or decrement (–) operator and the variable it applies to.

<?php
    // Correct.
    for ( $x = 0; $x < 10; $x++ ) {}

    // Incorrect.
    for ( $x = 0; $x < 10; $x ++ ) {}
    ++   $a; // Multiple spaces.
?>

Indentation

Your indentation should always match the structure of your argument. Use actual tabs, not spaces, as this provides for the best client compatibility.

If you have a block of code that would be easier to read if it were aligned, use spaces instead of tabs.

<?php
[tab]$x   = 'text value here';
[tab]$x2  = 'text value here2';
[tab]$x3 = 'text value here3';
[tab]$x4  = 'text value here4';
?>

Associative arrays are the next topic covered in this section. When an array has many items, each item should begin on a new line.

<?php
    $query = new Query( array( 'ref_id' => 95876 ) );
?>
<?php
    $args = array(
    [tab]'post_type'   => 'page',
    [tab]'post_author' => 95876,
    [tab]'post_status' => 'publish',
    );
    
    $query = new Query( $args );
?>

Note the comma after the final array item; this is suggested since it makes it simpler to adjust the array’s order and produces clearer differences when new items are added.

<?php
    $sample_array = array(
    [tab]'x'   => 'text value here',
    [tab]'x2'  => 'text value here 2',
    [tab]'x3'  => 'text value here 3',
    [tab]'x4'  => 'text value here 4',
    );
?>

For switch control structures, case statements must be indented one tab after the switch statement, and case contents must be indented one tab after the case condition statement. 

<?php
    switch ( $type ) {
    [tab]case 'var1':
    [tab][tab]some_function();
    [tab][tab]break;
    [tab]case 'var2':
    [tab][tab]some_function();
    [tab][tab]break;
    }
?>

As a general rule, tabs should be used at the beginning of the line for indentation, while spaces can be used for alignment in the middle of the line.

Remove Trailing Spaces

Remove trailing whitespace from each line’s conclusion. It is preferred to omit the closing PHP tag at the conclusion of a file.

If you employ the tag, remove any trailing spaces. A function body should not have any trailing blank lines.

Declaring Arrays

Using long array syntax ( array(1, 2, 3) ) to declare arrays is typically more understandable than using short array syntax ( [1, 2, 3] ), especially for persons with vision impairments.

Additionally, it is considerably more descriptive for novices. Arrays must be declared using the long array syntax.

Multiline Function Calls

When a function call is divided across many lines, each parameter must be on a distinct line. Single-line inline comments may occupy a separate line.

Each parameter must not exceed a single line in length. Parameter values that span many lines must be assigned to a variable and then given to the function call.

<?php
    $bar = array(
        'use_this' => true,
        'meta_key' => 'field_name',
    );
    $baz = sprintf(
        __( 'Hi, %s!', 'domain_text' ),
        $friend_name
    );

    $a = x(
        $x1,
        $x2,
        sprintf( __( 'My favorite food is %s.' ), 'pizza' )
);
?>

Type declarations

Before and after type declarations must have precisely one space.

There should be no space between the nullability operator (?) and the actual type, as it is considered part of the type declaration.

Class/interface/enum name-based type declarations must match the case of the declared class/interface/enum name, whereas keyword-based type declarations must be in lowercase.

There shouldn’t be a space between the closing brackets of a function declaration and the colon that starts a return-type declaration.

These rules apply to all structures allowing for type declarations: functions, closures, enums, catch conditions, as well as the PHP 7.4 arrow functions and typed properties.

<?php
    // Correct.
    function foo( Class_Name $parameter, callable $callable, int $number_of_things = 0 ) {
        // Do something.
    }

    function bar(
        Interface_Name&Concrete_Class $param_a,
        string|int $param_b,
        callable $param_c = 'default_callable'
    ): User|false {
        // Do something.
    }
    
    // Incorrect.
    function baz(Class_Name $param_a, String$param_b,      CALLABLE     $param_c )   :   ?   iterable   {
        // Do something.
    }
?>

Frequently Ask Questions (FAQs)

What are the coding standards in PHP?

  • A “coding style guide” PSR [PSR-1] MUST be followed when writing code.
  • Indenting code MUST be done with four spaces, not tabs.
  • There should be no hard limit on line length; the soft limit should be 120 characters, and lines should be 80 characters or less.
  • After the namespace declaration, there MUST be one blank line, and after the block of use declarations, there MUST be one blank line.
  • The opening braces for classes MUST go on the next line, and the closing braces MUST go on the next line after the body.
  • The opening braces for methods MUST go on the next line, and the closing braces MUST go on the next line after the body.
  • There must be one space after control structure keywords, but not after method and function calls.
  • All properties and methods must have visibility declared; abstract and final must be declared before visibility; static must be declared after visibility.
  • Control structures with opening braces MUST go on the same line, and structures with closing braces MUST go on the line after the body.
  • There MUST NOT be a space after opening parentheses for control structures, and there MUST NOT be a space before closing parentheses for control structures.

What are PHP coding standards?

Code standards consist of principles, procedures, and guidelines for producing code that is cleaner, more legible, and more efficient with fewer defects and errors.

In addition, they provide a standardized method for developers to construct highly functional programs.

Remember that coding standards are not subjective viewpoints; rather, they are actual guidelines that determine the programming style, techniques, and methods of your code.

They must be specified openly and made accessible to developers. Coding standards ensure that all programmers adhere to specific principles.

Therefore, every developer, including novices, can easily comprehend, debug, and maintain the code.

Your team’s source code should look as if it were written by a single developer in a single session. 

Is PHP standardized?

PHP Framework Interop Group has issued the PHP Standard Recommendation (PSR) as a PHP specification.

Similar to the Java Specification Request for Java, this document serves to standardize PHP programming ideas.

It accomplishes this by outlining a shared set of norms and expectations for formatting PHP code.

Summary

In summary, we’ve examined the PHP coding standards and demonstrated how to write correct code with examples.

Lastly, if you want to learn more about PHP, please leave a comment below. We’ll be happy to hear it!

Leave a Comment