Inheritance in PHP

Classes can contain subclasses and subclasses can in turn contain superclasses. For example, the class Person could be the superclass of the class PizzaDeliveryGuy.

This is illustrated in the following UML class diagram.

You can use the following sentence to ease the identification of a subclass and a superclass.

“… is …”

Examples: “PizzaDeliveryGuy is a Person”, “Beer is a Beverage”, “A GraduateStudent is a Student”.

The subclass inherits the public and protected attributes and methods of the superclass.  Besides that, the subclass may override the methods of the superclass or create new methods which belong to the subclass. For example, A PizzaDeliveryGuy inherits the name and age attributes and the Walk method from Person. The PizzaDeliveryGuy class has the extra ability to deliver pizza, hence the declaration of the DeliverPizza method.

The source code for the Person and PizzaDeliveryGuy class is listed below.

<?php

class Person {

  protected $name;
  protected $age;

  function __construct($name,$age){
    $this->name = $name;
    $this->age = $age;
  }

  public function Walk(){
    print $this->name.": Walking!\r\n";
  }
}

class PizzaDeliveryGuy extends Person {

  function __construct($name, $age){
    parent::__construct($name,$age);
  }

  function Walk(){
    print $this->name.": Roaming the streets!\r\n";
  }

  function DeliverPizza(){
    print $this->name.": Delivering pizza!\r\n";
  }
}

$regularPerson = new Person('Joe',40);
$regularPerson->Walk();

$pizzaDeliveryGuy = new PizzaDeliveryGuy('Luigi',30);
$pizzaDeliveryGuy->Walk();
$pizzaDeliveryGuy->DeliverPizza();

?>

Output:

Joe: Walking!
Luigi: Roaming the streets!
Luigi: Delivering pizza!

As you can see the PizzaDeliveryGuy instance prints a different message when the Walk method is called. That occurs because the PizzaDeliveryGuy class is overriding the regular Walk method with its own Walk method.  It also doesn’t contain declarations for the name and age attributes. Those attributes are inherited from the Person class and are reused in the PizzaDeliveryGuy class.

 

This entry was posted in PHP and tagged , , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Why ask?