Here, will create a class that contains a final method Method(), and as we know that we cannot override a final method, that's why it will generate a syntax error.
The source code to demonstrate the final keyword is given below. The given program is compiled and executed successfully.
<?php
//PHP program to demonstrate the final keyword.
class ParentClass
{
final public function Method()
{
printf("Parent::Method() called<br>");
}
}
class Child extends ParentClass
{
final public function Method()
{
printf("Child::Method() called<br>");
}
}
$ChildObj = new Child();
$ChildObj->Method();
?>
Output:
PHP Fatal error: Cannot override final method ParentClass::Method()
in /home/main.php on line 16
Explanation:
In the above program, we created a class that ParentClass that contains a method, which is declared as final, and then we inherited the ParentClass into Child class and override the method, but as we know that we cannot override a final method, that's why above program will generate a syntax error.
Program/Source Code:
The source code to demonstrate the final keyword is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we created a class that ParentClass that contains a method, which is declared as final, and then we inherited the ParentClass into Child class and override the method, but as we know that we cannot override a final method, that's why above program will generate a syntax error.