OOP Practical Examples — a practical guide to OOP practical examples PHP with clear examples you can reuse in real projects.
OOP Tutorial Series (64/65). Prefer one article? Read the complete OOP tutorial.
Short description
Practical examples connect theory to code you can reuse in apps and interviews.
Mini cart example
class CartItem {
public function __construct(public string $name, public int $priceCents, public int $qty = 1) {}
public function lineTotal(): int { return $this->priceCents * $this->qty; }
}
class Cart {
/** @var CartItem[] */
private array $items = [];
public function add(CartItem $item): void { $this->items[] = $item; }
public function total(): int {
return array_sum(array_map(fn (CartItem $i) => $i->lineTotal(), $this->items));
}
}