Abstract and final
Two keywords in PHP say what a class is for: abstract means a child must finish the job, final means nobody may change it. Both are checked when the class loads, not when a method is called.
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.
<?php abstract class Writer { abstract public function write(string $text): void; public function done(): void { echo "done", PHP_EOL; } } class EchoWriter extends Writer { public function write(string $text): void { echo $text, PHP_EOL; } } $w = new EchoWriter(); $w->write("hello"); $w->done(); try { new Writer(); } catch (Error $e) { echo get_class($e), ": ", $e->getMessage(), PHP_EOL; }
php abstract.php
hello
done
Error: Cannot instantiate abstract class Writer
The child filled in the open method, the shared method ran unchanged, and the direct construction of the abstract class was refused with a catchable error.
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.
<?php final class Money { public function __construct(public int $cents) { } } class Logger { final public function log(string $m): void { echo $m, PHP_EOL; } } class FileLogger extends Logger { // public function log(string $m): void {} would be refused: // Cannot override final method Logger::log() } $money = new Money(1099); echo $money->cents, PHP_EOL; $logger = new FileLogger(); $logger->log("written");
php final.php
1099
written
The final class was built and the final method was inherited by a child, which shows what stays allowed. The comment names the fatal error that an override would raise when the file loads.
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.
<?php interface Writable { public function write(string $text): void; } abstract class Writer implements Writable { public function done(): void { echo "done", PHP_EOL; } } final class Screen extends Writer { public function write(string $text): void { echo $text, PHP_EOL; } } $w = new Screen(); $w->write("hello"); $w->done(); echo $w instanceof Writable ? "writable" : "not writable", PHP_EOL;
php compare.php
hello
done
writable
One class carried the interface promise and the abstract class's method together, which is the combination the section describes.
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.
<?php abstract class Parser { abstract public function parse(string $in): array; } final class JsonParser extends Parser { public function parse(string $in): array { return json_decode($in, true); } } $p = new JsonParser(); echo json_encode($p->parse('{"a":1}')), PHP_EOL;
php design.php
{"a":1}
The abstract parent invited a child, the final child closed the family, and the parser itself only had to fill in one method.
Exercises
- Add a second child to the abstract writer and print what each one writes.
- Try to create the abstract class directly and print the error message.
- Extend the final class of the second section and read the message PHP returns.
- Make a class that implements two interfaces and extends one abstract class, then print both promises.
- Mark one method of a small helper final and explain why no child may change it.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What happens when you write
newwith an abstract class?Answer
PHP throws an Error that the class cannot be instantiated
The class is incomplete by design, and construction fails with a catchable Error.
-
What does
finalon a class prevent?Answer
Extending the class
A final class cannot be a parent; PHP stops the file that tries it.
-
What does
finalon a method prevent?Answer
Overriding it in a child class
Children may inherit the method, but a declaration of the same name is refused.
-
How many parent classes and interfaces can one class have?
Answer
One parent and many interfaces
PHP is single inheritance for classes, and a class may implement several interfaces.
-
What does this program print?
<?php abstract class Writer { abstract public function write(string $text): void; public function done(): void { echo "done"; } } class EchoWriter extends Writer { public function write(string $text): void { echo $text; } } $w = new EchoWriter(); $w->write("hello"); $w->done();Answer
hellodone
Both calls print without a line break, so the two words follow each other.
-
What does this program print?
<?php abstract class Writer { abstract public function write(string $text): void; } try { new Writer(); } catch (Error $e) { echo get_class($e); }Answer
Error
An abstract class is a plain Error case, not an Exception or a TypeError.
-
What does this program print?
<?php final class Money { public function __construct(public int $cents) { } } $money = new Money(1099); echo $money->cents;Answer
1099
final only blocks extension, so the class is created and the promoted property prints its value.
-
What does this program print?
<?php class Logger { final public function log(string $m): void { echo $m; } } class FileLogger extends Logger { } $logger = new FileLogger(); $logger->log("written");Answer
written
A final method can be inherited and called; only overriding it is refused.
-
What does this program print?
<?php interface Writable { public function write(string $text): void; } abstract class Writer implements Writable { public function done(): void { echo "done"; } } final class Screen extends Writer { public function write(string $text): void { echo $text; } } $w = new Screen(); $w->write("hello"); $w->done();Answer
hellodone
The interface method and the shared method both print, and neither adds a separator.
-
Why mark a small helper class final?
Answer
To say that its behaviour is complete and no child may change it
The keyword records the design decision, so a reader knows the logic is not meant to be replaced.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev