abhai
3 June 2023
In PHP, the `final` keyword is used to restrict the inheritance and overriding of methods and classes. Here's what it does in different contexts:
- Final methods: When you declare a method as `final` within a class, it means that the method cannot be overridden by any subclass that extends that class. It effectively prevents the subclass from redefining the method implementation.
<?php class ParentClass { final public function someMethod() { // Method implementation } } class ChildClass extends ParentClass { // This will cause an error since overriding final method is not allowed public function someMethod() { // New method implementation } }
- Final classes: When you declare a class as `final`, it means that the class cannot be extended by any other class. In other words, it prevents inheritance from that class.
<?php final class FinalClass { // Class implementation } class ChildClass extends FinalClass { // This will cause an error since extending a final class is not allowed }
The final keyword is also relevant in other OO programming languages like Java, C# and C++.