Skip to main content
PHP, despite its widespread use and continuous improvements, still has common anti-patterns that can lead to bugs, security vulnerabilities, and maintenance problems. Here are the most important anti-patterns to avoid when writing PHP code.
PHP’s loose comparison (==) can lead to unexpected results due to type juggling. Always use strict comparison (===) to compare both value and type.
Always sanitize user input to prevent SQL injection, XSS, and other security vulnerabilities. Use prepared statements for database queries.
The mysql_* functions are deprecated and removed in PHP 7+. Use mysqli_* or PDO instead for database operations.
Use namespaces to organize your code and avoid naming conflicts, especially in larger applications.
Never use eval() as it allows arbitrary code execution. Use safer alternatives specific to your use case.
Use Composer’s autoloading (PSR-4) instead of manual require/include statements to automatically load classes when needed.
Use type declarations (scalar types, return types, nullable types) to make your code more robust and self-documenting.
Short tags (<?) are not enabled on all servers and may conflict with XML declarations. Always use full PHP tags (<?php) or the echo shorthand (<?=).
Use proper error handling with try-catch blocks and exceptions to gracefully handle errors.
Don’t use superglobals ($_GET, $_POST, etc.) directly. Validate and sanitize input or use a request abstraction.
Don’t hardcode sensitive information like database credentials or API keys. Use environment variables or a .env file (with proper security).
Use dependency injection to make your code more testable and flexible.
Use interfaces to define contracts and allow for different implementations.
Magic methods (__get, __set, etc.) can make code harder to understand and debug. Use them sparingly and prefer explicit properties and methods.
Use Composer to manage dependencies instead of downloading libraries manually.
Separate your code into Model (data), View (presentation), and Controller (logic) components.
Follow PHP-FIG standards (PSR-1, PSR-2/PSR-12, etc.) for consistent, readable code.
Use static analysis tools like PHPStan, Psalm, or PHP_CodeSniffer to catch potential issues early.
Configure sessions securely to prevent session hijacking and other attacks.