PHP program to demonstrate the final keyword

Here, we are going to demonstrate the final keyword in PHP.
Submitted by Nidhi, on November 21, 2020 [Last updated : March 13, 2023]

Final Keyword Example

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.

PHP code to demonstrate the example of final keyword

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.

PHP Class & Object Programs »



Related Programs



All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.