Skip to content

Commit

Permalink
added interface documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
withinboredom committed Nov 16, 2024
1 parent f14b093 commit c7155c3
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
40 changes: 40 additions & 0 deletions drafts/records.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
40 changes: 40 additions & 0 deletions published/records.ptxt
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,46 @@ record User(string $name, string $emailAddress) {
}
</code>

==== Implementing Interfaces ====

A **record** can implement interfaces, but it cannot extend other records or classes, but may use traits:

<code 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;
}
</code>

==== 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.
Expand Down

0 comments on commit c7155c3

Please sign in to comment.