Learn how to write clean and maintainable code with these 10 practical tips.
Writing clean and maintainable code in PHP follows the same principles as in other programming languages. Here are 10 tips tailored specifically for PHP to help you write clean, readable, and maintainable code:
camelCase
for variables and functions, PascalCase
for classes).Example:
// Bad
$a = 10;
function fn() {}
// Good
$userAge = 10;
function calculateDiscount() {}
Example:
// Bad
function processOrder($order) {
// Validate order
// Calculate total
// Send confirmation email
// Save to database
}
// Good
function validateOrder($order) {}
function calculateTotal($order) {}
function sendConfirmationEmail($order) {}
function saveOrderToDatabase($order) {}
int
, string
, array
, etc.) for function parameters and return types.Example:
// Bad
function add($a, $b) {
return $a + $b;
}
// Good
function add(int $a, int $b): int {
return $a + $b;
}
Example:
// Bad
if ($user->isLoggedIn()) {
if ($user->hasPermission('edit')) {
// Do something
}
}
// Good
if (!$user->isLoggedIn()) {
return;
}
if (!$user->hasPermission('edit')) {
return;
}
// Do something
Example:
// Bad
$taxRate = 0.07;
// Good
define('TAX_RATE', 0.07);
$taxRate = TAX_RATE;
Example:
// Bad
function calculateArea($shape, $width, $height = null) {
if ($shape === 'rectangle') {
return $width * $height;
} elseif ($shape === 'circle') {
return pi() * $width * $width;
}
}
// Good
class Rectangle {
public function calculateArea($width, $height): float {
return $width * $height;
}
}
class Circle {
public function calculateArea($radius): float {
return pi() * $radius * $radius;
}
}
require
or include
.Example:
# Install a package with Composer
composer require monolog/monolog
// Autoload dependencies
require 'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
Example:
// PHPUnit test example
use PHPUnit\Framework\TestCase;
class MathTest extends TestCase {
public function testAdd() {
$this->assertEquals(4, add(2, 2));
$this->assertEquals(0, add(-1, 1));
}
}
Example:
# Install PHP-CS-Fixer
composer require friendsofphp/php-cs-fixer
# Run PHP-CS-Fixer
vendor/bin/php-cs-fixer fix src/
Example:
/**
* Calculate the discounted price.
*
* @param float $price The original price.
* @param float $discountRate The discount rate (e.g., 0.1 for 10%).
* @return float The discounted price.
*/
function calculateDiscountedPrice(float $price, float $discountRate): float {
return $price * (1 - $discountRate);
}
By following these tips, you’ll write PHP code that is clean, maintainable, and easy to collaborate on.