ADVERTISEMENT
ADVERTISEMENT

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

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.

Program/Source Code:

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 »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.