OOPs Tutorials
- What is OOPs
- Access Modifier
- Constructor
- Destructor
- Polymorphism
- Inheritence
- Method Overriding
- Abstract class
- Interface
- Traits
- This keyword
- static keyword
- Final keyword
- Class Constant
- Exception Handling
- Binding in php
- tostring in php
- Object Iteration
- Reflection
- Magic methods
- Namespaces
- CRUD Function
- OOPs CRUD
- CRUD Example
Important Links
What is final keyword?
<?php
final class BaseClass {
public function myMethod() {
echo "BaseClass method called";
}
}
//this will cause Compile error
class DerivedClass extends BaseClass {
public function myMethod() {
echo "DerivedClass method called";
}
}
$obj = new DerivedClass();
$obj->myMethod();
?>
( ! ) Fatal error: Class DerivedClass may not inherit from final class (BaseClass) in D:\wamp\www\OOPs\index.php on line 13
Final method
A final method is a method that cannot be overridden. To declare a method as final, you need to prefix the function name with the ‘final’ keyword.
<?php
class BaseClass {
final public function myMethod() {
echo "BaseClass method called";
}
}
class DerivedClass extends BaseClass {
//this will cause Compile error
public function myMethod() {
echo "DerivedClass method called";
}
}
$c = new DerivedClass();
$c->myMethod();
?>
( ! ) Fatal error: Cannot override final method BaseClass::myMethod() in D:\wamp\www\OOPs\index.php on line 13
DerivedClass extends from BaseClass. BaseClass has the method myMethod() declared as final and this cannot be overridden. In this case the compiler causes a compile error.