PHP OOP in 8+ looks like other C-family languages: classes, public/protected/private, interfaces, and traits for reuse without inheritance. Use constructor property promotion, readonly where it fits, and namespaces with PSR-4 autoload. Prefer composition over deep extends trees.
This PHP cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Class:
class User { public function __construct(public int $id) {} }. - Visibility:
publicAPI,privateinternals,protectedfor children. - Interface: Contract of methods. A class
implementsone or more. - Trait:
use Logger;inside a class to copy methods — watch collisions. - abstract: Base class you cannot instantiate. Force children to implement methods.
- namespace:
namespace App\Services;+use App\Models\User. - static:
self::/static::(late static binding). Do not turn every helper into static soup. - readonly: PHP 8.2+ class or properties that cannot be reassigned after construct.
Copy-paste examples
Promoted properties and an interface
Keep constructors thin. Put PDO in a repository, not in every model.
<?php
declare(strict_types=1);
interface Clock
{
public function now(): int;
}
final class SystemClock implements Clock
{
public function now(): int
{
return time();
}
}
final class Invoice
{
public function __construct(
public readonly int $id,
public readonly int $total,
private Clock $clock,
) {}
public function stamped(): string
{
return $this->id . '-' . $this->clock->now();
}
}Common mistakes
- God classes that query SQL, send email, and render HTML.
- Public properties mutated from controllers with no invariants.
new PDOinside every method instead of injecting a connection.- Traits that depend on undeclared properties — invisible coupling.
FAQ
- Do I need OOP for a small PHP page? Not always. A function plus PDO is fine. Classes help when the file grows past “a script.”
- extends vs implements?
extendsis one parent class.implementsis one or more interfaces. Prefer interfaces at module boundaries.
- What is PSR-4? A mapping from namespace prefixes to folders so Composer can autoload
App\Foofromsrc/Foo.php.
Related PHP cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.