bg_image
header

PSR-2

PSR-2 is a coding style guideline for PHP developed by the PHP-FIG (Framework Interop Group) to make code more readable and consistent, allowing development teams to collaborate more easily. The abbreviation “PSR” stands for “PHP Standards Recommendation”.

Key Points in PSR-2:

  1. Indentation: Use four spaces for indentation instead of tabs.
  2. Line Length: Code should ideally not exceed 80 characters per line, with an absolute maximum of 120 characters.
  3. File Structure: Each PHP file should either contain only classes, functions, or executable code, but not a mix.
  4. Braces: Opening braces { for classes and methods should be on the next line, whereas braces for control structures (like if, for) should be on the same line.
  5. Spaces: Place a space between control keywords and parentheses, as well as around operators (e.g., =, +).

Example

Here’s a simple example following these guidelines:

<?php

namespace Vendor\Package;

class ExampleClass
{
    public function exampleMethod($arg1, $arg2 = null)
    {
        if ($arg1 === $arg2) {
            throw new \Exception('Arguments cannot be equal');
        }

        return $arg1;
    }
}

PSR-2 has since been expanded and replaced by PSR-12, which includes additional rules to further improve code consistency.