Q:

PHP program to demonstrate the final keyword

belongs to collection: PHP Classes & Objects Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Classes & Objects Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
PHP program to demonstrate the method overloading ... >>
<< PHP program to demonstrate the method overriding...