PHP Programming/Inheritance

Inheritance is the extension of a class. A child class has all the properties and methods of its parent class.

Inheritance is one of the core concepts in object oriented programming. PHP supports inheritance like other object oriented language supports inheritance.

Example 1: pets

edit

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()
   {
   }
}
?>

Example 2: persons

edit

Consider two person one the parent and his child. By definition the child would have inherited certain properties from the parent. So the child might have all the characteristics of the parent and in addition to that the child might have additional characteristics. With this analogy in mind consider two classes Person and programmer the base class has the following code.

<?php
class Person{
    var $legs=2;
    var $head=1;

    function walk(){
        echo "Walk";
    }
}
?>

The Person class has two attributes $legs and $head and it has one method walk. Suppose there is another class programmer . The programmer class has all this attributes and methods so you can define it in again or you can just inherit from the Person class. So you can define the programmer class as follows.

<?php
    class programmer extends Person{
    
    }
?>

No this that all we have to do is just use the keyword extends and then followed by base class then the all the properties of the base class are inherited which means we can do this.

<?php

$jedai = new programmer();
echo $jedai->legs;
echo $jedai->head;
echo $jedai->walk();

?>

Traits

edit

Initially, PHP was a language of simple inheritance. However since PHP 5.4.0, a data structure called "trait" allows the multiple inheritance.

Example:

<?php
trait MyTrait1
{
	function Hello() {
		print 'Hello';
	}
}

trait MyTrait2
{
	function World() {
		print 'World';
	}
}

class MyClasse1
{
	use MyTrait1;
	use MyTrait2;
	
	function __construct() {
		$this->Hello();
		$this->World();
	}
}

$Test = new MyClasse1;
?>