diff --git a/drafts/records.md b/drafts/records.md index 7cfd58f..28d32fe 100644 --- a/drafts/records.md +++ b/drafts/records.md @@ -289,6 +289,46 @@ record User(string $name, string $emailAddress) { } ``` +### Implementing Interfaces + +A **record** can implement interfaces, but it cannot extend other records or classes, but may use traits: + +```php +interface Vehicle {} + +interface Car extends Vehicle { + public function drive(): void; +} + +interface SpaceShip extends Vehicle { + public function launch(): void; +} + +record FancyCar(string $model) implements Car { + public function drive(): void { + echo "Driving a Fancy Car {$this->model}"; + } +} + +record SpaceCar(string $model) implements Car, SpaceShip { + public function drive(): void { + echo "Driving a Space Car {$this->model}"; + } + + public function launch(): void { + echo "Launching a Space Car {$this->model}"; + } +} + +record Submarine(string $model) implements Vehicle { + use Submersible; +} + +record TowTruct(string $model, private Car $towing) implements Car { + use Towable; +} +``` + ### Mental models and how it works From the perspective of a developer, declaring a record declares an object with the same name. diff --git a/published/records.ptxt b/published/records.ptxt index 032d57a..c839785 100644 --- a/published/records.ptxt +++ b/published/records.ptxt @@ -245,6 +245,46 @@ record User(string $name, string $emailAddress) { } +==== Implementing Interfaces ==== + +A **record** can implement interfaces, but it cannot extend other records or classes, but may use traits: + + +interface Vehicle {} + +interface Car extends Vehicle { + public function drive(): void; +} + +interface SpaceShip extends Vehicle { + public function launch(): void; +} + +record FancyCar(string $model) implements Car { + public function drive(): void { + echo "Driving a Fancy Car {$this->model}"; + } +} + +record SpaceCar(string $model) implements Car, SpaceShip { + public function drive(): void { + echo "Driving a Space Car {$this->model}"; + } + + public function launch(): void { + echo "Launching a Space Car {$this->model}"; + } +} + +record Submarine(string $model) implements Vehicle { + use Submersible; +} + +record TowTruct(string $model, private Car $towing) implements Car { + use Towable; +} + + ==== Mental models and how it works ==== From the perspective of a developer, declaring a record declares an object with the same name. The developer can consider the record function (the inline constructor) as a factory function that creates a new object or retrieves an existing object from an array.