PSR-12 is a coding style guideline defined by the PHP-FIG (PHP Framework Interoperability Group). It builds on PSR-1 (Basic Coding Standard) and PSR-2 (Coding Style Guide), extending them to include modern practices and requirements.
PSR-12 aims to establish a consistent and readable code style for PHP projects, facilitating collaboration between developers and maintaining a uniform codebase.
namespace declaration.use statements should follow the namespace declaration.namespace App\Controller;
use App\Service\MyService;
use Psr\Log\LoggerInterface;
{ for a class or method must be placed on the next line.public, protected, private) is mandatory for all methods and properties.class MyClass
{
private string $property;
public function myMethod(): void
{
// code
}
}
public function myFunction(
int $param1,
string $param2
): string {
return 'example';
}
{ must be on the same line as the control structure.if ($condition) {
// code
} elseif ($otherCondition) {
// code
} else {
// code
}
[]) for arrays.$array = [
'first' => 'value1',
'second' => 'value2',
];
?.public function getValue(?int $id): ?string
{
return $id !== null ? (string) $id : null;
}
<?php tag and must not include a closing ?> tag.PSR-12 extends PSR-2 by:
PSR-12 is the standard for modern and consistent PHP code. It improves code quality and simplifies collaboration, especially in team environments. Tools like PHP_CodeSniffer or PHP-CS-Fixer can help ensure adherence to PSR-12 effortlessly.