Abstract and final
Abstract classes
An abstract class cannot be created with new. It exists to be extended by children.
It holds shared code and declares open methods that each child fills in. Common logic lives in one place.
abstract class Writer {
abstract public function write(string $text): void;
public function done(): void {
echo "done";
}
}
Final classes and methods
The final keyword blocks extension of a class or override of a method. The marked code is complete as written.
Use final for small helpers where changed behavior would break callers. Readers see at once that no child tweaks the logic.
final class Money {
public function __construct(public int $cents) {}
}
class Logger {
final public function log(string $m): void {
echo $m;
}
}
Abstract vs interface
An interface lists what an object can do, while an abstract class also shows how part of it works. The interface is pure promise, the class is promise plus tools.
One class can use many interfaces but extend only one parent. Reach for interfaces to combine skills, and for abstract classes to share code.
interface Writable {
public function write(string $text): void;
}
abstract class Writer implements Writable {
}
Design intent
Mark a class abstract when it needs children to be useful, and final when it is already complete. The keyword records your intent for the next reader.
Clear intent guides growth. New code extends where extension is welcome and stops where behavior must stay fixed.
abstract class Parser {
abstract public function parse(string $in): array;
}
final class JsonParser extends Parser {
public function parse(string $in): array {
return [];
}
}
Next: Traits advanced
Автор статьи: Arthur Isaev