This tutorial will help us to see the use of final keyword with a method of a class and a class individually.
Example:
class parentClass {
public function test1() {
echo "This is test1 method of parentClass";
}
final public function test2() {
echo "This is test2 method of parentClass that is made final";
}
}
OUTPUT:
$obj = new parentClass();
$obj->test2();
//This is test2 method of parentClass that is made final
// But when we extend the parentClass
class childClass extends parentClass {
public function test2() {
echo "on overriding the final method test2 a fatal error will be thrown ";
}
}
OUTPUT:
It gives a Fatal error
When we make a class final
final class parentClass {
public function test1() {
echo "This is test1 method of parentClass";
}
public function test2() {
echo "This is test2 method of parentClass";
}
}
class ChildClass extends parentClass {
}
Here we get a Fatal error as we cannot extend the final class.
1 Comment(s)