Final Keyword
suggest changeDef: Final Keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended
Final Method
class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
public function moreTesting() {
echo "ChildClass::moreTesting() called\n";
}
}
// Results in Fatal error: Cannot override final method BaseClass::moreTesting()
Final Class:
final class BaseClass {
public function test() {
echo "BaseClass::test() called\n";
}
// Here it doesn't matter if you specify the function as final or not
final public function moreTesting() {
echo "BaseClass::moreTesting() called\n";
}
}
class ChildClass extends BaseClass {
}
// Results in Fatal error: Class ChildClass cannot extend final class BaseClass
Final constants: Since PHP 8.1, final public const NAME = ...; stops a child class from overriding that constant. Before 8.1, final was not allowed on constants; declare them with const. Since PHP 8.4, properties can be final as well. Private methods, other than the constructor, cannot be final as of PHP 8.0.
Why do I have to use final****?
- Preventing massive inheritance chain of doom
- Encouraging composition
- Force the developer to think about user public API
- Force the developer to shrink an object’s public API
- A
finalclass can always be made extensible extendsbreaks encapsulation- You don’t need that flexibility
- You are free to change the code
When to avoid final****: Final classes only work effectively under following assumptions:
- There is an abstraction (interface) that the final class implements
- All of the public API of the final class is part of that interface
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents