Writing Clean Code in PHP: Best Practices and Examples

oktay
3 min readMay 11, 2023

--

Writing clean and maintainable code is essential for any software project, including those written in PHP. Here are some tips and tricks for writing clean code in PHP:

Follow a consistent coding style: Adopt a consistent coding style throughout the project. This includes the use of indentation, spacing, and naming conventions for variables, functions, and classes. Consider using a coding standard like PSR-2 or PSR-12 to ensure consistency.

Use meaningful and descriptive names: Use descriptive and meaningful names for variables, functions, classes, and methods. This helps in understanding the code’s purpose and makes it easier to maintain in the future.

// Bad example ❌
$var1 = 10;
function func($a, $b) {
// code...
}

// Good example ✅
$numberOfUsers = 10;
function calculateSum($num1, $num2) {
// code...
}

Avoid overly complex code: Write simple and concise code that is easy to understand. Avoid overly complex code structures, nested if statements, and deeply nested loops. Break down complex tasks into smaller, simpler tasks that are easier to manage.

Avoid hardcoding values: Avoid hardcoding values like file paths, database connections, and API endpoints in your code. Instead, store these values in configuration files or environment variables.

// Bad example ❌
$databaseHost = 'localhost';
$databaseUsername = 'root';
$databasePassword = 'password';

// Good example ✅
// Store configuration in a separate file or use environment variables
$databaseHost = getConfig('DB_HOST');
$databaseUsername = getConfig('DB_USERNAME');
$databasePassword = getConfig('DB_PASSWORD');

Use comments and documentation: Use comments to explain the purpose of the code, how it works, and any potential issues or limitations. Use documentation tools like PHPDoc to generate documentation from code comments.

/**
* Calculate the sum of two numbers.
*
* @param int $num1 The first number.
* @param int $num2 The second number.
* @return int The sum of the two numbers.
*/
function calculateSum($num1, $num2) {
// code...
}

Use exception handling: Use exception handling to handle errors and unexpected situations in your code. Use custom exception classes to provide more context and information about the error.

try {
// code...
} catch (CustomException $e) {
// handle the specific exception
} catch (Exception $e) {
// handle general exceptions
}

Avoid global variables: Avoid the use of global variables as they can make it difficult to track the flow of data through your code. Instead, pass data through function arguments or use dependency injection.

function doSomething($data) {
// code...
}

// Bad example ❌
function process() {
global $data;
doSomething($data);
}

// Good example ✅
function process($data) {
doSomething($data);
}

Use consistent error handling: Use consistent error handling throughout your code. Use the same error handling method for all types of errors to avoid confusion and maintainability issues.

// Bad example ❌
function validateInput($input) {
if (empty($input)) {
echo 'Error: Input cannot be empty.';
return;
}
// code...
}

// Good example ✅
function validateInput($input) {
if (empty($input)) {
throw new InvalidArgumentException('Input cannot be empty.');
}
// code...
}

Use meaningful error messages: Use meaningful error messages that provide useful information to users or developers. Avoid generic error messages that do not provide enough context to troubleshoot issues.

function divideNumbers($numerator, $denominator) {
if ($denominator === 0) {
throw new InvalidArgumentException('Cannot divide by zero. Please provide a non-zero value for the denominator.');
}
return $numerator / $denominator;
}

Test your code: Write unit tests for your code to ensure that it works as intended and to catch any potential issues early on. Use automated testing tools like PHPUnit to simplify the testing process.

function calculateSum($num1, $num2) {
return $num1 + $num2;
}
use PHPUnit\Framework\TestCase;

class CalculateSumTest extends TestCase {
public function testCalculateSum() {
$result = calculateSum(2, 3);
$this->assertEquals(5, $result);
}
}

--

--