Final keyword in PHP
In PHP, the final
keyword is used to restrict the inheritance of a class or the overriding of a method. When a class or method is declared as final, it cannot be extended or overridden by any child class.
- Final Class: A final class cannot be extended by any other class. If we try to extend a final class, a fatal error will occur. For example:
final class MyClass {
// class code
}
class MyChildClass extends MyClass {
// error: MyClass cannot be extended
}
- Final Method: A final method cannot be overridden by any child class. If we try to override a final method, a fatal error will occur. For example:
class MyClass {
final public function myMethod() {
// method code
}
}
class MyChildClass extends MyClass {
public function myMethod() {
// error: myMethod() cannot be overridden
}
}
- Final Variable:
In PHP, we cannot declare a variable as final. However, we can achieve the same functionality by using the
const
keyword to define a constant. Constants cannot be changed once they are defined. For example:
class MyClass {
const MY_CONSTANT = 10;
}
echo MyClass::MY_CONSTANT; // output: 10
In conclusion, the final
keyword in PHP is used to restrict the inheritance of a class or the overriding of a method. It helps to ensure that certain classes or methods cannot be modified or extended, which can be useful in preventing unexpected behavior in our code.