You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: published/records.ptxt
+40Lines changed: 40 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -245,6 +245,46 @@ record User(string $name, string $emailAddress) {
245
245
}
246
246
</code>
247
247
248
+
==== Implementing Interfaces ====
249
+
250
+
A **record** can implement interfaces, but it cannot extend other records or classes, but may use traits:
251
+
252
+
<code php>
253
+
interface Vehicle {}
254
+
255
+
interface Car extends Vehicle {
256
+
public function drive(): void;
257
+
}
258
+
259
+
interface SpaceShip extends Vehicle {
260
+
public function launch(): void;
261
+
}
262
+
263
+
record FancyCar(string $model) implements Car {
264
+
public function drive(): void {
265
+
echo "Driving a Fancy Car {$this->model}";
266
+
}
267
+
}
268
+
269
+
record SpaceCar(string $model) implements Car, SpaceShip {
270
+
public function drive(): void {
271
+
echo "Driving a Space Car {$this->model}";
272
+
}
273
+
274
+
public function launch(): void {
275
+
echo "Launching a Space Car {$this->model}";
276
+
}
277
+
}
278
+
279
+
record Submarine(string $model) implements Vehicle {
280
+
use Submersible;
281
+
}
282
+
283
+
record TowTruct(string $model, private Car $towing) implements Car {
284
+
use Towable;
285
+
}
286
+
</code>
287
+
248
288
==== Mental models and how it works ====
249
289
250
290
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.
0 commit comments