---
title: PHP Best Practices
type: agent/instruction
tags: [php, web]
---

{{h1}}PHP

{{h2}}Modern PHP
- PHP 8.0+ features
- Strict types: `declare(strict_types=1)`
- Type declarations
- Named arguments
- Match expressions over switch

{{h2}}Organisation
- Namespaces for all code
- PSR-4 autoloading
- One class per file
- Composer for dependencies
- PSR-12 coding style

{{h2}}Type Safety
- Enable strict types
- Type all parameters/returns
- Union types when appropriate
- Static analysis (PHPStan, Psalm)

{{h2}}Error Handling
- Exceptions for errors
- Custom exception classes
- Catch specific exceptions
- Log appropriately

{{h2}}Security
- Prepared statements
- Validate/sanitize input
- `password_hash()` for passwords
- `htmlspecialchars()` for XSS
- CSRF tokens

{{h2}}Database
- PDO or ORM (Doctrine, Eloquent)
- Always prepared statements
- Transactions for integrity
- Connection pooling

{{h2}}OOP
- Visibility keywords
- Readonly properties
- Constructor property promotion
- Composition over inheritance
- Interfaces for contracts

{{h2}}Functions
- Small and focused
- Type declarations
- Return early
- Named arguments for optional

{{h2}}Performance
- OPcache in production
- Cache expensive operations
- Generators for large datasets
- Profile before optimising

{{h2}}Avoid
- Don't use short tags (`<?`)
- Don't use global variables
- Don't suppress errors with `@`
- Don't use `eval()`
