Guide to style and good practices PHP


Many times I find hard code to read, as it is not structured or indented. In SOes we can find multiple examples of this.

Searching the site for a question that addresses this issue, I found this @ A.Cedano , Convention of names in PHP , but does not really address the theme of style or good practices. I also did not find any question that addresses PSR 1 and 2.

If I could find another similar one referring to html, css and js. Official style guides for HTML, CSS and Javascript

That is why I am asking this question:

What are the tips or recommendations regarding the style and order of the code that should be taken into account when developing with PHP?

asked by Xerif 24.11.2017 в 00:34

2 answers


The best style guide we can take when developing a project in PHP is at PHP Standards Recommendations (PSR) . Specifically PSR 1 and 2 that refer to basic coding and coding style respectively.

PSR-1 Basic coding standard

  • Use only the <?php ?> and / or <?= ?> tag, no other open / close tag (example <? ?> , <% %> , etc ...).
  • Always use UTF-8 encoding without BOM for PHP code.
  • Files must declare classes, functions, constants, etc ... or execute logic (for example, generate results, change .ini settings, etc.) but should not do both .
  • Namespaces and classes must follow PSR-0 or PSR-4.
  • Class names are declared in StudlyCaps .
  • Constants are declared in uppercase with underscore separators ( MI_CONSTANTE ).
  • The names of the methods are declared in camelCase .

PSR-2 Coding style guide

  • Use 4 spaces for indentation , do not use tabs.
  • The lines must be less than 80 characters . Longer lines should be divided into multiple lines.
  • There should not be more than one statement per line.
  • keywords or reserved keywords must be in lower case .
  • null , true and false must be in minuscule.
  • There must be a blank line after the declaration of namespace .
  • There must be a blank line after the use statements.
  • Keywords extends e implements must be declared on the same line as the name of the class.
  • Opening keys { in the classes and methods must go to the next line, and the closing key } must go to the next line after the body.
  • Visibility ( public , protected or private ) must always be declared in all properties and methods.
  • There must be no blank spaces between the name of the functions and methods and the parentheses ( ) (example: miFuncion() ).
  • In the argument list, there should not be a space before each comma if there should be a space after each comma.
  • The arguments of the method with defaults must go to the end of the argument list.
  • The opening key { for control structures (example: if ) must follow on the same line, and the closing key } must pass to the next line after the body.


Namespace and use

namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

// code

Extends and Implements

class ClassName extends ParentClass implements \ArrayAccess, \Countable
    // constants, properties, methods


class ClassName
    public $foo = null;

    // methods


public function fooBarBaz($arg1, &$arg2, $arg3 = [])
    // method body

Methods with an argument in several lines

public function aVeryLongMethodName(
    ClassTypeHint $arg1,
    array $arg3 = []
) {
    // method body

abstract, final and static

namespace Vendor\Package;

abstract class ClassName
    protected static $foo;

    abstract protected function zim();

    final public static function bar()
        // method body

Calls to methods and functions

// llamada a función
bar($arg2, $arg3);

// llamada a método

// llamada a método estático con argumentos
Foo::bar($arg2, $arg3);

// llamada a método con argumentos multilinea

if, elseif and else


if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;

switch, case

switch ($expr) {
    case 0:
        echo 'First case, with a break';
    case 1:
        echo 'Second case, which falls through';
        // no break
    case 2:
    case 3:
    case 4:
        echo 'Third case, return instead of break';
        echo 'Default case';

while and do while

do {
    // structure body;
} while ($expr);


for ($i = 0; $i < 10; $i++) {
    // for body


foreach ($iterable as $key => $value) {
    // foreach body

try and catch

try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body

Source: link

answered by 24.11.2017 / 00:34

Complementing the answer of @Xerif, it is opportune to mention that these PSRs are proposed today, maintained and implemented by the PHP Framework Interoperability Group which has weight because it brings together representatives of the most important frameworks and libraries of the PHP ecosystem:

  • CakePHP
  • Composer
  • Drupal
  • Magento
  • Phalcon
  • phpBB
  • Slim
  • Symphony
  • Yii
  • Zend Framework

(The only big one that is not there is Laravel, but Taylor Otwell left the FIG because he did not have time to participate in the debates, vote or propose, but part of Laravel adopts some PSRs)

In the end, although this group does not decide the features that are in the core of the PHP engine, they can decide how to operate with them adopting conventions that allow interoperability between frameworks.

For example, PHP does not have a native class that handles dependency injection. A construct like that everyone implements it as he wants. However, thanks to the existence of the PHP-FIG, and to which an agreement was reached among its members, they took out the PSR-11, which specifies how a container of dependencies should behave. Nowadays if you install a framework that uses symfony/dependency-injection as an injector, you are free to change it by php-di/php-di because they implement the same interface.

The same applies to handling $request and $response in the routes. Today, most frameworks adhere to the PSR-7. That means for example that if you want to change your app's engine from Silex to Slim you can leave your routes as they are.

Although this does not have to do with the style, those PSR are vital for the PHP ecosystem and reinforce the cohesion between the different actors.

answered by 24.11.2017 в 12:28