What are PHP PSRs?
PHP Standard Recommendation (PSR) is a PHP specification published by PHP Framework Interop Group, it serves to standardize PHP programming concepts.
PSR-1: Basic Coding Standard
The PSR-1 (Basic Coding Standard) is a PHP-FIG (PHP Framework Interop Group) standard that defines basic coding conventions to ensure interoperability between PHP projects. It sets fundamental guidelines on naming conventions, file structures, and class definitions.
1. Files MUST Use UTF-8 Encoding Without BOM
All PHP files must use UTF-8 encoding without a BOM (Byte Order Mark).
✅ Correct:
<?php
echo "Hello, world!";
❌ Incorrect (with BOM, which can cause issues):
<EF BB BF><?php
echo "Hello, world!";
2. Files SHOULD Either Declare Symbols (Classes, Functions, Constants) or Cause Side Effects (Not Both)
A PHP file should either define classes, functions, or constants or cause side effects (e.g., outputting data or modifying headers) not both.
✅ Correct (Separate Files):
// File: Game.php (Only declares a class)
<?php
class Game {
public function start() {
echo "Game started!";
}
}
// File: start.php (Only causes a side effect)
<?php
require 'Game.php';
$game = new Game();
$game->start();
❌ Incorrect (Mixing Declarations and Side Effects in One File):
<?php
class Game {
public function start() {
echo "Game started!";
}
}
$game = new Game(); // Side effect
$game->start();
3. Namespaces and Class Names MUST Follow PSR-4 Standards
- Class names must follow
StudlyCaps
(PascalCase). - Namespaces should also use
StudlyCap
✅ Correct:
namespace Library\Games;
class ChessGame {
public function play() {
echo "Game started!";
}
}
❌ Incorrect (Using Snake_Case or lowercase):
namespace library_games; // Incorrect
class chess_game { // Incorrect
public function play() {
echo "Game started!";
}
}
4. Class Constants MUST Be in Uppercase with Underscores
Class constants should be defined in all uppercase letters with underscores separating words.
✅ Correct:
class Game {
const MAX_PLAYERS = 4;
}
❌ Incorrect (Lowercase or camelCase):
class Game {
const maxPlayers = 4; // Incorrect
}
5. Method and Function Names MUST Use camelCase
Method and function names should be in camelCase.
✅ Correct:
function getGameStatus() {
return "Running";
}
class Game {
public function startGame() {
echo "Started!";
}
}
❌ Incorrect (Using snake_case or PascalCase for methods and functions):
function get_game_status() { // Incorrect
return "Running";
}
class Game {
public function StartGame() { // Incorrect
echo "Started!";
}
}
Summary of PSR-1
Rule | Description |
---|---|
UTF-8 Encoding | PHP files must use UTF-8 without BOM |
Separate Declarations and Side Effects | A file should either declare symbols (classes, functions) or cause side effects, not both |
Namespaces & Class Names | Use StudlyCaps for class names and proper namespacing |
Class Constants | Must be UPPER_CASE_WITH_UNDERSCORES
|
Method & Function Names | Must be in camelCase
|
Top comments (0)