Coding Standards in PHP - Fahim1505/CSE327-Alumni-Student GitHub Wiki
Coding standards and guidelines ensure consistency, readability and maintainability, thereby allowing efficient development of the project as multiple collaborators work on different aspects of it. They also ensure error detection in the early phases, which reduces the extra cost incurred by the software project. Furthermore, they increase understandability by reducing the complexity of the overall code. The following section provides a series of coding standards which adhere to the PSR (PHP Standard Recommendations), particularly, the PSR-1 and PSR-12.
-
General
-
1.1: Files
-
PHP Tags
- PHP code MUST use the long
<?php ?>tags or the short-echo<?= ?>tags; it MUST NOT use the other tag variations. - The closing
?>tag MUST be omitted from files containing only PHP.
- PHP code MUST use the long
-
Character Encoding
- PHP code MUST use only UTF-8 without BOM.
-
File Format
- All PHP files MUST use the Unix LF (linefeed) line ending only.
- All PHP files MUST end with a non-blank line, terminated with a single LF.
-
-
1.2: Lines
- There MUST NOT be a hard limit on line length.
- The soft limit on line length MUST be 120 characters.
- Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD be split into multiple subsequent lines of no more than 80 characters each.
- There MUST NOT be trailing whitespace at the end of lines.
- There MUST NOT be more than one statement per line.
-
1.3: Indenting
- Code MUST use an indent of 4 spaces for each indent level and MUST NOT use tabs for indenting.
-
1.4: Keywords and Types
- All PHP reserved keywords and types MUST be in lower case.
- Any new types and keywords added to future PHP versions MUST be in lower case.
- Short form of type keywords MUST be used, that is,
boolinstead ofboolean,intinstead ofintegeretc.
-
-
Declare Statements, Namespace, and Import Statements
-
Class names MUST be declared in
StudlyCaps. -
Code written for PHP 5.3 and after MUST use formal namespaces.
For example:
<?php // PHP 5.3 and later: namespace Vendor\Model; class Foo { }
-
The header of a PHP file may consist of several different blocks. If present, each of the blocks below MUST be separated by a single blank line and MUST NOT contain a blank line. Each block MUST be in the order listed below, although blocks that are not relevant may be omitted:
- Opening
<?phptag. - File-level docblock.
- One or more declare statements.
- The namespace declaration of the file.
- One or more class-based
useimport statements. - One or more function-based
useimport statements. - One or more constant-based
useimport statements. - The remainder of the code in the file.
- Opening
-
When a file contains a mix of HTML and PHP, any of the above sections may still be used. If so, they MUST be present at the top of the file, even if the remainder of the code consists of a closing PHP tag and then a mixture of HTML and PHP.
-
When the opening
<?phptag is on the first line of the file, it MUST be on its own line with no other statements unless it is a file containing markup outside of PHP opening and closing tags -
Import statements MUST never begin with a leading backslash as they must always be fully qualified.
The following example illustrates a complete list of all blocks, where Foobar is an example class:
<?php /** *This file contains an example of coding styles. */ declare(strict_types=1); namespace Vendor\Package; use Vendor\Package\{ClassA as A, ClassB, ClassC as C}; use Vendor\Package\SomeNamespace\ClassD as D; use Vendor\Package\AnotherNamespace\ClassE as E; use function Vendor\Package\{functionA, functionB, functionC}; use function Another\Vendor\functionD; use const Vendor\Package\{CONSTANT_A, CONSTANT_B, CONSTANT_C}; use const Another\Vendor\CONSTANT_D; /** * FooBar is an example class. */ class FooBar { // ... additional PHP code ... }
-
When wishing to declare strict types in files containing markup outside PHP opening and closing tags, the declaration MUST be on the first line of the file and include an opening PHP tag, the strict types declaration and closing tag.
For example:
<?php declare(strict_types=1) ?> <html> <body> <?php // ... additional PHP code ... ?> </body> </html
-
-
Classes, Properties and Methods
-
The term "class" refers to all classes, interfaces, and traits.
-
Any closing brace MUST NOT be followed by any comment or statement on the same line.
-
When instantiating a new class, parentheses MUST always be present even when there are no arguments passed to the constructor.
For example:
new Foo();
-
3.1: Extends and Implements
-
The
extendsandimplementskeywords MUST be declared on the same line as the class name. -
The opening brace for the class MUST go on its own line; the closing brace for the class MUST go on the next line after the body.
-
Opening braces MUST be on their own line and MUST NOT be preceded or followed by a blank line.
-
Closing braces MUST be on their own line and MUST NOT be preceded by a blank line.
For example:
<?php namespace Vendor\Package; use FooClass; use BarClass as Bar; use OtherVendor\OtherPackage\BazClass; class ClassName extends ParentClass implements \ArrayAccess, \Countable { // constants, properties, methods }
-
Lists of implements and, in the case of interfaces, extends MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one interface per line.
For example:
<?php namespace Vendor\Package; use FooClass; use BarClass as Bar; use OtherVendor\OtherPackage\BazClass; class ClassName extends ParentClass implements \ArrayAccess, \Countable, \Serializable { // constants, properties, methods }
-
-
3.2: Using Traits
-
The
usekeyword used inside the classes to implement traits MUST be declared on the next line after the opening brace.For example:
<?php namespace Vendor\Package; use Vendor\Package\FirstTrait; class ClassName { use FirstTrait; }
-
Each individual trait that is imported into a class MUST be included one-per-line and each inclusion MUST have its own use import statement.
For example:
<?php namespace Vendor\Package; use Vendor\Package\FirstTrait; use Vendor\Package\SecondTrait; use Vendor\Package\ThirdTrait; class ClassName { use FirstTrait; use SecondTrait; use ThirdTrait; }
-
-
3.3: Properties and Constants
-
Visibility MUST be declared on all properties.
-
Visibility MUST be declared on all constants if your project PHP minimum version supports constant visibilities (PHP 7.1 or later).
-
The var keyword MUST NOT be used to declare a property.
-
There MUST NOT be more than one property declared per statement.
-
Property names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.
-
There MUST be a space between type declaration and property name.
-
Whatever naming convention is used SHOULD be applied consistently within a reasonable scope. That scope may be vendor-level, package-level, class-level, or method-level.
The following is an example of a property declaration:
<?php namespace Vendor\Package; class ClassName { public $foo = null; public static int $bar = 0; }
-
-
3.4: Methods and Functions
-
Method names MUST be declared in camelCase().
-
Visibility MUST be declared on all methods.
-
Method names MUST NOT be prefixed with a single underscore to indicate protected or private visibility. That is, an underscore prefix explicitly has no meaning.
-
Method and function names MUST NOT be declared with space after the method name.
-
The opening brace MUST go on its own line, and the closing brace MUST go on the next line following the body.
-
There MUST NOT be a space after the opening parenthesis, and there MUST NOT be a space before the closing parenthesis.
The following example illustrates a method declaration:
<?php namespace Vendor\Package; class ClassName { public function fooBarBaz($arg1, &$arg2, $arg3 = []) { // method body } }
The following example illustrates a function declaration:
<?php function fooBarBaz($arg1, &$arg2, $arg3 = []) { // function body }
-
-
3.5: Method and Function Arguments
-
In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.
-
Method and function arguments with default values MUST go at the end of the argument list.
For example:
<?php namespace Vendor\Package; class ClassName { public function foo(int $arg1, &$arg2, $arg3 = []) { // method body } }
-
Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.
-
When the argument list is split across multiple lines, the closing parenthesis and opening brace MUST be placed together on their own line with one space between them.
For example:
<?php namespace Vendor\Package; class ClassName { public function aVeryLongMethodName( ClassTypeHint $arg1, &$arg2, array $arg3 = [] ) { // method body } }
-
When you have a return type declaration present, there MUST be one space after the colon followed by the type declaration. The colon and declaration MUST be on the same line as the argument list closing parenthesis with no spaces between the two characters.
For example:
<?php declare(strict_types=1); namespace Vendor\Package; class ReturnTypeVariations { public function functionName(int $arg1, $arg2): string { return 'foo'; } public function anotherFunction( string $foo, string $bar, int $baz ): string { return 'foo'; } }
-
-
3.6:
abstract,staticandfinal-
When present, the abstract and final declarations MUST precede the visibility declaration.
-
When present, the static declaration MUST come after the visibility declaration
For example:
<?php namespace Vendor\Package; abstract class ClassName { protected static $foo; abstract protected function zim(); final public static function bar() { // method body } }
-
-
3.7: Method and Function Calls
-
When making a method or function call, there MUST NOT be a space between the method or function name and the opening parenthesis, there MUST NOT be a space after the opening parenthesis, and there MUST NOT be a space before the closing parenthesis.
-
In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.
For example:
<?php bar(); $foo->bar($arg1); Foo::bar($arg2, $arg3);
-
-
-
Control Structures
The general style rules for control structures are as follows:
-
There MUST be one space after the control structure keyword
-
There MUST NOT be a space after the opening parenthesis
-
There MUST NOT be a space before the closing parenthesis
-
There MUST be one space between the closing parenthesis and the opening brace
-
The structure body MUST be indented once
-
The body MUST be on the next line after the opening brace
-
The closing brace MUST be on the next line after the body
The body of each structure MUST be enclosed by braces. This standardizes how the structures look and reduces the likelihood of introducing errors as new lines get added to the body.
-
4.1:
if,elseifandelseThe following example shows an
ifstructure:<?php if ($expr1) { // if body } elseif ($expr2) { // elseif body } else { // else body; }
-
The keyword
elseifSHOULD be used instead ofelse ifso that all control keywords look like single words. -
Expressions in parentheses MAY be split across multiple lines, where each subsequent line is indented at least once. When doing so, the first condition MUST be on the next line.
-
The closing parenthesis and opening brace MUST be placed together on their own line with one space between them. Boolean operators between conditions MUST always be at the beginning or at the end of the line, not a mix of both.
For example:
<?php if ( $expr1 && $expr2 ) { / if body } elseif ( $expr3 && $expr4 ) { // elseif body }
-
-
4.2:
switch,caseThe following example shows a
switchstructure:<?php switch ($expr) { case 0: echo 'First case, with a break'; break; case 1: echo 'Second case, which falls through'; // no break case 2: case 3: case 4: echo 'Third case, return instead of break'; return; default: echo 'Default case'; break; }
-
The
casestatement MUST be indented once fromswitch, and thebreakkeyword (or other terminating keywords) MUST be indented at the same level as thecasebody. -
There MUST be a comment such as
// no breakwhen fall-through is intentional in a non-emptycasebody.
-
-
4.3:
while,do-whileThe following example shows a
whilestatement:<?php while ($expr) { // structure body }
- Expressions in parentheses MAY be split across multiple lines, where each subsequent line is indented at least once. When doing so, the first condition MUST be on the next line. The closing parenthesis and opening brace MUST be placed together on their own line with one space between them. Boolean operators between conditions MUST always be at the beginning or at the end of the line, not a mix of both. These rules apply to the
switchstatement as well.
For example:
<?php while ( $expr1 && $expr2 ) { // structure body }
- Similarly, in a
do while statement, expressions in parentheses MAY be split across multiple lines, where each subsequent line is indented at least once. When doing so, the first condition MUST be on the next line. Boolean operators between conditions MUST always be at the beginning or at the end of the line, not a mix of both.
For example:
<?php do { // structure body; } while ( $expr1 && $expr2 );
- Expressions in parentheses MAY be split across multiple lines, where each subsequent line is indented at least once. When doing so, the first condition MUST be on the next line. The closing parenthesis and opening brace MUST be placed together on their own line with one space between them. Boolean operators between conditions MUST always be at the beginning or at the end of the line, not a mix of both. These rules apply to the
-
4.4:
forThe following example shows a
forstatement:<?php for ($i = 0; $i < 10; $i++) { // for body }
-
Expressions in parentheses MAY be split across multiple lines, where each subsequent line is indented at least once. When doing so, the first expression MUST be on the next line.
-
The closing parenthesis and opening brace MUST be placed together on their own line with one space between them.
The following example illustrates these:
<?php for ( $i = 0; $i < 10; $i++ ) { // for body }
-
-
4.5:
foreachThe following example shows a
foreachstatement:<?php foreach ($iterable as $key => $value) { // foreach body }
-
4.6:
try,catch,finallyThe following example shows a
try-catch-finallystatement:<?php try { // try body } catch (FirstThrowableType $e) { // catch body } catch (OtherThrowableType | AnotherThrowableType $e) { / catch body } finally { // finally body }
-
-
Operators
-
Style rules for operators are grouped by arity (the number of operands they take).
-
When space is permitted around an operator, multiple spaces MAY be used for readability purposes.
-
All operators not described here are left undefined.
-
5.1: Unary Operators
-
The increment/decrement operators MUST NOT have any space between the operator and operand.
For example:
$i++; ++$j;
-
-
5.2: Binary Operators
-
All binary arithmetic, comparison, assignment, bitwise, logical, string, and type operators MUST be preceded and followed by at least one space:
For example:
if ($a === $b) { $foo = $bar ?? $a ?? $b; } elseif ($a > $b) { $foo = $a + $b * $c; }
-
-
-
Closures
-
Closures MUST be declared with a space after the
functionkeyword, and a space before and after theusekeyword. -
The opening brace MUST go on the same line, and the closing brace MUST go on the next line following the body.
-
There MUST NOT be a space after the opening parenthesis of the argument list or variable list, and there MUST NOT be a space before the closing parenthesis of the argument list or variable list.
-
In the argument list and variable list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.
-
Closure arguments with default values MUST go at the end of the argument list.
-
If a return type is present, it MUST follow the same rules as with normal functions and methods; if the
usekeyword is present, the colon MUST follow theuselist closing parentheses with no spaces between the two characters. Style rules for operators are grouped by arity (the number of operands they take).For example:
<?php $closureWithArgs = function ($arg1, $arg2) { // body }; $closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) { // body }; $closureWithArgsVarsAndReturn = function ($arg1, $arg2) use ($var1, $var2): bool { // body };
-
Argument lists and variable lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument or variable per line.
-
-
Anonymous Classes
-
Anonymous Classes MUST follow the same guidelines and principles as closures in the above section.
For example:
<?php $instance = new class {};
-
The opening brace MAY be on the same line as the
classkeyword so long as the list ofimplementsinterfaces does not wrap. If the list of interfaces wraps, the brace MUST be placed on the line immediately following the last interface.For example:
<?php // Brace on the same line $instance = new class extends \Foo implements \HandleableInterface { // Class content }; // Brace on the next line $instance = new class extends \Foo implements \ArrayAccess, \Countable, \Serializable { // Class content };
-