In PHP, final is a keyword used in OOP to prevent further modification of classes or methods.
1. Final Class
A final class cannot be extended (inherited) by any other class.
This is useful when you want to lock the class’s functionality so no one can override or modify it via inheritance.
Example:
final class PaymentGateway {
public function processPayment() {
echo "Processing payment...";
}
}
// ❌ This will cause a fatal error
class MyGateway extends PaymentGateway {
// Error: Class MyGateway may not inherit from final class (PaymentGateway)
}
💡 Use case: You make a class final when you want to keep its implementation fixed for security, performance, or design reasons.
2. Final Method
A final method in PHP cannot be overridden in child classes,
but the class itself can still be inherited.
Example:
class BankAccount {
final public function getAccountNumber() {
return "1234567890";
}
public function deposit($amount) {
echo "Depositing $amount";
}
}
class MyAccount extends BankAccount {
// ❌ This will cause a fatal error
public function getAccountNumber() {
return "0000000000";
}
}
💡 Use case: You make a method final when you want subclasses to inherit it exactly as it is without any change.
Quick Difference Table
| Feature | Final Class | Final Method |
|---|---|---|
| Can be inherited? | ❌ No | ✅ Yes |
| Can be overridden? | ❌ Not applicable (no inheritance) | ❌ No |
| Purpose | Lock whole class | Lock specific method |
