In PHP, the “final” keyword is used to prevent a class, method, or property from being overridden or extended by its child classes. When a class, method, or property is marked as final, it cannot be changed or extended by any child class.
Here’s an example of using the “final” keyword in PHP:
class ParentClass {
final public function doSomething() {
echo "Doing something in the parent class\n";
}
}
class ChildClass extends ParentClass {
public function doSomething() {
echo "Doing something in the child class\n"; // This will result in a fatal error
}
}
In this example, the “ParentClass” defines a final method “doSomething”, which cannot be overridden by any child class. The “ChildClass” attempts to override the “doSomething” method, which results in a fatal error since it is marked as final in the parent class.
The “final” keyword can also be used to prevent a class from being extended, or to prevent a property from being overridden. Here are some examples:
final class FinalClass {
// ...
}
class ChildClass extends FinalClass {
// This will result in a fatal error
// ...
}
class ParentClass {
final protected $property = 'some value';
}
class ChildClass extends ParentClass {
protected $property = 'another value';
// This will result in a fatal error
}
In these examples, the “FinalClass” is marked as final, which means it cannot be extended by any child class. Similarly, the “property” in the “ParentClass” is marked as final, which means it cannot be overridden by any child class.
The “final” keyword is useful when you want to ensure that a certain aspect of your code cannot be changed or extended by other developers, or when you want to prevent accidental changes to critical parts of your code.