PHP: OOP – code examples
Class with Inheritance
Use case: Bundle data and behavior, e.g. users, products or game characters.
<?php
class Tier {
public function __construct(protected string $name) {}
public function sprich(): string {
return "{$this->name} makes a sound";
}
}
class Hund extends Tier {
public function sprich(): string {
return "{$this->name} says Woof!";
}
}
echo (new Hund("Rex"))->sprich(), "\n";Constructor promotion (protected string $name) declares and sets the property in one step. Hund inherits from Tier and overrides sprich.
Enum with Method
OOP#enum#match#php81
Use case: Model fixed choice values (status, roles, payment methods) in a type-safe way instead of working with strings.
<?php
enum Status: string {
case Offen = "offen";
case Erledigt = "erledigt";
public function label(): string {
return match ($this) {
self::Offen => "To do",
self::Erledigt => "Done",
};
}
}
$s = Status::from("erledigt");
echo $s->name, " ", $s->value, " ", $s->label(), "\n";
var_dump(Status::tryFrom("xyz"));Enums exist since PHP 8.1. from throws a ValueError for an invalid value, tryFrom returns null. With match ($this) you attach behavior to the enum.
Immutable Value Object
OOP#readonly#constructor promotion#dto
Use case: Transport data between layers (DTO) or model money/coordinates immutably.
<?php
final class Produkt {
public function __construct(
public readonly string $name,
public readonly float $preis,
) {}
public function mitPreis(float $neu): static {
return new static($this->name, $neu);
}
}
$p = new Produkt("Coffee", 4.5);
$q = $p->mitPreis(5.0);
echo $p->preis, " -> ", $q->preis, "\n";
try { $p->preis = 1.0; } catch (Error $e) { echo $e->getMessage(), "\n"; }readonly prevents later changes. Changes produce a new object ("with" methods). The error reads Cannot modify readonly property Produkt::$preis.