PHP Best Practices: PSR-1

Published Feb 22, 2017Last updated Mar 13, 2017
PHP Best Practices: PSR-1

When you're programming, it's important to follow certain best practices in order to make your code easy to read and understand. This is an essential point when you're working in a team or if your code is going to be used by another developer. However, it is also important when we're working alone on a project.

What is PSR-1?

PSR-1 is a basic coding standard. It's oriented to the content of PHP files and the names of the classes and methods.

It aims to ensure a high technical level of interoperability between PHP code.

It covers topics like Files, PHP tags, character encoding, namespace, class names, class constants, properties and methods

Overview of Rules

Some of these rules are:

  • Files MUST use only
    <?php and ?> tags.

    The reason? If you accidentally add code after the PHP closing tag, it’ll be interpreted as HTML.

  • Files MUST use only UTF-8 without BOM for PHP code.

    Depending on your code editor the PHP code will be saved in different formats. You need to configure your editor to use UTF-8 encoding, and include a byte order mark (BOM).

  • Namespaces and classes MUST follow an "autoloading" PSR.

    This means each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name.

  • Class names MUST be declared in StudlyCaps. <br/>class MyNewClass extends Parent{...}

    StudlyCaps means that the first capital of each subword is capitalized.

  • Class constants MUST be declared in all upper case with underscore separators. <br/>const DATE_TODAY = '2016-11-11';

    This helps you to see clearer the difference between a constant, a method, a variable, etc.

  • Method names MUST be declared in camelCase (). public function getNameById($id){...}

    camelCase is a special case of StudlyCaps. First letter lowercase, but after that all words capitalized and run together

  • PHP code MUST use the long <?php ?> tags or the short-echo <?= ?> tags; it MUST NOT use the other tag variations.

This is a resume of the standards that should be used. For more details you can take a look at The PSR-1 and this PHP Interview Questions Sample Answer. I hope this help you to improve your code!

Discover and read more posts from Sonia Vázquez
get started