PHP program to demonstrate the method overriding

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

Method Overriding Example

Here, we will understand the concept of method overriding using the PHP program. In the method overriding, we can define a method with the same name in the parent and child class.

PHP code to implement method overriding

The source code to demonstrate the method overriding is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the method overriding.
class ParentClass
{
    public function Method()
    {
        printf("Parent::Method() called<br>");
    }
}
class Child extends ParentClass
{
    public function Method()
    {
        printf("Child::Method() called<br>");
    }
}

$ParentObj = new ParentClass();
$ParentObj->Method();

$ChildObj = new Child();
$ChildObj->Method();
?>

Output

Parent::Method() called
Child::Method() called

Explanation

In the above program, we created two classes ParentClass and Child and we inherited the ParentClass into Child class. Both classes contain a method with the same name. It means we have overridden the method Method().

At last, we created the objects of both classes and called the methods using objects that will call methods according to objects and print appropriate messages on the webpage.

PHP Class & Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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