PHP - Custom Type Overriding methods

Introduction

When extending from a class, we get all the methods of the parent class.

Consider the following code:

Demo

<?php
    class Talkable { 
        public function sayHi() { 
            echo "Hi, I am pops."; 
        } //from   w w  w  . j a v  a  2s. co m
    } 

    class Child extends Talkable{ 
        public function sayHi() { 
            echo "Hi, I am a child."; 
        } 
    } 

    $pops = new Talkable(); 
    $child = new Child(); 
    echo $pops->sayHi(); // Hi, I am pops. 
    echo $child->sayHi(); // Hi, I am Child. 
?>

Result

The method sayHi() has been overridden.

When invoking it from a child's point of view, we will be using it rather than the one inherited from its father.

To reference the inherited one, reference it with the keyword parent.

class Child extends Talkable{ 
    public function sayHi() { 
        echo "Hi, I am a child."; 
        parent::sayHi(); 
    } 
 } 

$child = new Child(); 
echo $child->sayHi(); // Hi, I am Child. Hi I am pops. 

When overriding, the method has to have at least as much visibility as the one inherited.

If we inherit a protected one, we can override it with another protected or a public one, but never with a private one.

Related Topic