PHP PSR Standards
PSR stands for PHP Standards Recommendations. These standards are published by the PHP Framework Interop Group (PHP-FIG) to improve interoperability between PHP frameworks and libraries.
1. PSR-1: Basic Coding Standard
This standard outlines the basic rules to ensure a high level of technical interoperability between shared PHP code.
- Files MUST use only
<?phpand<?=. - Files MUST use only UTF-8 without BOM.
- Class names MUST be declared in
StudlyCaps. - Method names MUST be declared in
camelCase. - Constants MUST be declared in all upper case with underscore separators.
2. PSR-4: Autoloading Standard
PSR-4 describes a specification for autoloading classes from file paths. It replaces the older PSR-0 standard.
- It maps namespaces to file system directories.
- Example:
\Namespace\ClassNamemaps topath/to/project/src/ClassName.php. - This is the standard used by Composer.
// composer.json
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
3. PSR-12: Extended Coding Style
PSR-12 extends and replaces PSR-2. It provides a coding style guide for projects.
- Code MUST use 4 spaces for indenting, not tabs.
- Lines SHOULD NOT be longer than 120 characters.
- Opening braces for classes MUST go on the next line.
- Opening braces for methods MUST go on the next line.
- Visibility (public, protected, private) MUST be declared on all properties and methods.
<?php
namespace Vendor\Package;
class ClassName
{
public function fooBarBaz($arg1, &$arg2, $arg3 = [])
{
// method body
}
}