Last modified on 13 August 2010, at 13:23

PHP Programming/Inheritance

Inheritance is the extension of a class. A child class has all the properties and methods of its parent class. For example, pets generally share similar characteristics, regardless of what type of animal they are. Pets eat, and sleep, and can be given names. However the different types of pet also have their own methods: dogs bark and cats meow. Below is an implementation of this:

<?php
class Pet
{
   var $_name;
 
   function Pet($name)
   {
      $this->_name = $name;
   }
 
   function eat()
   {
   }
 
   function sleep()
   {
   }
}
 
class Dog extends Pet
{
   function bark()
   {
   }
}
 
class Cat extends Pet
{
   function meow()
   {
   }
}
 
$dog = new Dog("Max");
$dog->eat();
$dog->bark();
$dog->sleep();
 
$cat = new Cat("Misty");
$cat->eat();
$cat->meow();
$cat->sleep();
?>

Likewise we could use the PHP5 syntax for our inherited class:

<?php
class Pet
{
   var $_name
 
   public function __construct($name)
   {
      $this->_name = $name;
   }
 
   function eat()
   {
   }
 
   function sleep()
   {
   }
}
?>