PHP - Overriding Methods in the Parent Class

Introduction

To create a child class whose methods are different from the corresponding methods in the parent class, override methods from parent.

PHP can override a parent class's method in the child class.

To do this, simply create a method with the same name in the child class.

Then, when that method name is called for an object of the child class, the child class's method is run instead of the parent class's method:

Demo

<?php
          class ParentClass {
            public function someMethod() {
              // (do stuff here)
            }/*from   www  .  jav  a2 s .c o m*/
          }

          class ChildClass extends ParentClass {
            public function someMethod() {
              // This method is called instead for ChildClass objects
            }
          }

    $parentObj = new ParentClass;
    $parentObj->someMethod();  // Calls ParentClass::someMethod()
    $childObj = new ChildClass;
    $childObj->someMethod();   // Calls ChildClass::someMethod()
?>

Here, the parent class's method is called when accessed from an object of the parent class, and the child class's method is called when using an object of the child class.

The following example code shows how you can use inheritance to distinguish grapes from other fruit:

Demo

<?php

    class Fruit {
      public function peel() {
        echo "I'm peeling the fruit...\n";
      }/*  w w  w .  j a  v  a2 s. c om*/

      public function slice() {
        echo "I'm slicing the fruit...\n";
      }

      public function eat() {
        echo "I'm eating the fruit. Yummy!\n";
      }

      public function consume() {
        $this->peel();
        $this->slice();
        $this->eat();
      }
    }

    class Grape extends Fruit {
      public function peel() {
        echo "No need to peel a grape!\n";
      }

      public function slice() {
        echo "No need to slice a grape!\n";
      }
    }
echo "Consuming an apple...";
$apple = new Fruit;
$apple->consume();

echo "Consuming a grape...";
$grape = new Grape;
$grape->consume();

?>

Result

Related Topic