PHP Extend Multiple Classes [Multiple Inheritance]

You may have question in your mind like "Can I extend a class using more than 1 class in PHP?" that's why you are here. Well the direct answer is no but you can tweak your way through it. But how? The answer is using interfaces.

PHP does not allow multiple inheritance for classes but this is not true for interfaces, an interface may inherit from any number of interfaces as long as none of the interfaces it inherits from declares a method with the same name as those declared in child interface.

To explain it with some PHP code let us take an example, consider three entities a person, a teacher and HOD (Head of the Department). A teacher is a person if we are to define three classes for each entity teacher will extend person class. HOD is a person and a teacher too, so he must inherit from both but PHP does not allow this.

An interface is like a pure abstract class consisting only method declarations and some constants so we can declare the behaviour of teacher in interface named teacherInterface and now HOD class can extend person and implement the interface teacherInterface. You can have as many interfaces as you want.

PHP Multiple Inheritance using Interfaces

<?php

class person 
{
  var $name;
  var $age;
}

class teacher extends person
{
  var $qualification;
  var $subject;
  var salary;
  function teaches()
  {
     echo "$name teaches $subject";
  }
}

interface teacherInterface
{
  public function teaches();
}

// implements keyword is used to implement an interface
class HOD extends person implements teacherInterface
{
  var salary;

  // define the teaches function here

}?>
That's it you can use this concept to implement multiple inheritance in any of your cases.

[If you are a beginner and want any help please msg us on our Facebook page, you can find the link on the bottom of the page.]