Skip to content

PHP Style Guide

Background

This document is intended to outline the style rules for PHP here at Miva. This style guide applies to anywhere that PHP is written. In general we adhere to the PSR-12 Extended Coding Style with the exception of using tabs over spaces to maintain consistency across our code base. It is recommended to read through the PSR-12 Style Guide, but outlined here are some of the more important aspects.

Key Points

General

Files

Files must use the Unix LF line ending.

All PHP files must have a single empty line at the end.

The closing ?> tag should be omitted.

Lines

There is a soft limit of 120 characters per line.

There must not be any trailing whitespace at the end of lines.

Indenting

Code should be indented using tabs. Avoid using spaced for indentation.

Declare Statements, Namespace, and Import Statements

PHP files should follow this structure:

  • Opening <?php tag
  • Namespace declaration of the file
  • One or more class-based use imports
  • One or more function-based use imports
  • One or more constant-based use imports
  • The rest of the code

Class Properties and Constants

Visibility must be declared on all properties and constants.

Do not use the var keyword to declare a property.

Only one declaration statement per line.

There must be a space between any type declarations and the property name.

// Example
<?php
namespace Vendor\Package;

class FooBar
{
    public $name = 'Dr. Michio Kaku';
    public string $profession = 'Theoretical Physicist';
}

Methods and Functions

Visibility must be declared on all methods and functions.

Method names should not have any prefix.

Method and function names are NOT followed by a space character.

The opening curly brace must be on its own line.

// Example
<?php
namespace Vendor\Package;

class FooBar
{
    public function fizzBuzz($arg1, $arg2)
    {
        return arg1 + arg2;
    }
}

if, elseif, else

The condition being evaluated should be surrounded with parenthesis.

There should be a space before and after the condition.

Use elseif in place of else if

Incorrect
<?php

if( $expr1 === true )
{
    doSomething($expr1);
}
else if( $expr2 === true )
{
    doSomethingElse($expr2);
}
else
{
    doLastCondition();
}
Correct
<?php

if ($expr1 === true) {
    doSomething($expr1);
} elseif ($expr2 === true) {
    doSomethingElse($expr2);
} else {
    doLastCondition();
}