PHP Final Keyword
The final
keyword in PHP is used to prevent class inheritance or method overriding. There are two main uses of the final
keyword:
- Preventing Class Inheritance: When you declare a class as
final
, it cannot be extended (inherited) by any other class. - Preventing Method Overriding: When you declare a method as
final
, it cannot be overridden in any subclass.
Here are examples to demonstrate both uses:
Example 1: Preventing Class Inheritance
<?php
final class BaseClass {
public function sayHello() {
echo "Hello from BaseClass!";
}
}
// This will cause an error
class ChildClass extends BaseClass {
public function sayHello() {
echo "Hello from ChildClass!";
}
}
$base = new BaseClass();
$base->sayHello();
// Uncommenting the following lines will cause an error
// $child = new ChildClass();
// $child->sayHello();
?>
Output:
Hello from BaseClass!
If you try to uncomment the ChildClass
definition, PHP will throw an error:
Fatal error: Class ChildClass may not inherit from final class (BaseClass)
Example 2: Preventing Method Overriding
<?php
class BaseClass {
public final function sayHello() {
echo "Hello from BaseClass!";
}
}
class ChildClass extends BaseClass {
// This will cause an error
public function sayHello() {
echo "Hello from ChildClass!";
}
}
$base = new BaseClass();
$base->sayHello();
// Uncommenting the following lines will cause an error
// $child = new ChildClass();
// $child->sayHello();
?>
Output:
Hello from BaseClass!
If you try to uncomment the sayHello
method in ChildClass
, PHP will throw an error:
Fatal error: Cannot override final method BaseClass::sayHello()
Summary
- Declaring a class as
final
prevents other classes from inheriting it. - Declaring a method as
final
prevents subclasses from overriding it.
Using the final
keyword is useful when you want to ensure certain parts of your code remain unchanged or unextended to maintain stability and consistency in your application.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.