PHP Overriding Methods

In this chapter you will learn:

  1. What is Overriding Methods
  2. How to override a method
  3. Example - subclasses
  4. Preserving the Functionality of the Parent Class

What

To create a child class whose methods are different from the corresponding methods in the parent class by overriding a parent class's method in the child class.

How

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:


<?PHP//from j  a  v a 2  s .  c  om
class ParentClass { 
  public function someMethod() { 
    // (do stuff here) 
  } 
} 
     
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()  
?>

Example

PHP allows us to redefine methods in subclasses. This is done by redefining the method inside the child class:


<?PHP//from   j  a  v  a 2s .c om
class Dog {
    public function bark() {
       print "Dog";
    }
}

class Puppy extends Dog {
   public function bark() {
      print "Puppy";
   }
}
?>

Preserving the Functionality of the Parent Class

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

parent::someMethod();

<?php /*j a  va 2  s .  co m*/
    class Fruit { 
      public function peel() { 
        echo "peeling the fruit.\n"; 
      } 
      public function slice() { 
        echo "slicing the fruit.\n"; 
      } 
            
      public function eat() { 
        echo "eating the fruit. \n"; 
      } 
            
      public function consume() { 
        $this-> peel(); 
        $this-> slice(); 
        $this-> eat(); 
      } 
    } 
    class Banana extends Fruit { 
        public function consume() { 
          echo " < p > I'm breaking off a banana... < /p > "; 
          parent::consume(); 
        } 
     } 

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

Next chapter...

What you will learn in the next chapter:

  1. Why do we need final keywords
  2. Syntax to use final keywords
Home » PHP Tutorial » PHP Class Definition
Concept for Object Oriented Design
PHP Class Definition
PHP Create Object from Class
PHP Class Properties
PHP Iterating Object Properties
PHP Class Inheritance
PHP Overriding Methods
PHP final Classes and Methods
PHP Abstract Class
PHP Class Access Control Modifiers
PHP Class Constructor
PHP Class Destructors
PHP Class Magic Methods