PHP - Preserving the Functionality of the Parent Class

Introduction

To override the method of a parent class in your child class, and also use some of the functionality that is in the parent class's method.

You can do this by calling the parent class's overridden method from within the child class's method.

To call an overridden method, you write parent:: before the method name:

parent::someMethod();

Demo

<?php

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

      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 Banana extends Fruit {
          public function consume() {
            echo "I'm breaking off a banana...\n";
            parent::consume();
          }
         }

        $banana = new Banana;
        $banana->consume();
?>

Result

Related Topic