Home > PHP, PHP5 OOPS Tutorials > PHP5 Tutorials – Abstract Class and Interface

PHP5 Tutorials – Abstract Class and Interface

February 3rd, 2008 admin Leave a comment Go to comments

In this post, we learn what is an abstract class and an interface.

  • What is an Abstract Class?
  • Private methods cannot be Abstract
  • What is an Interface?
  • Defining an Interface
  • Abstract Class v/s Interface

What is an Abstract Class?

An abstract class is a class with or without data members that provides some functionality and leaves the remaining functionality for its child class to implement. The child class must provide the functionality not provided by the abstract class or else the child class also becomes abstract.

Objects of an abstract and interface class cannot be created i.e. only objects of concrete class can be created

To define a class as Abstract, the keyword abstract is to be used e.g. abstract class ClassName { }

Example of Abstract Class

 
abstract class Furniture {
	private $height, width, length;
 
	public function setData($h, $w, $l) {
		$this->height = $h;
		$this->width = $w;
		$this->length = $l;
	}
 
        //this function is declared as abstract and hence the function
        //body will have to be provided in the child class
	public abstract function getPrice();
 
}
 
 
class BookShelf extends Furniture {
 
   private $price;
 
   public setData($h, $w, $l, $p) {
      parent::setData($h, $w, $l);
      $this->price = $p;
   }
 
 
   //this is the function body of the parent abstract method
   public function getPrice() {
      return $this->price;
   }
}

In the above example, the method getPrice() in class Furniture has been declared as Abstract. This means that its the responsibility of the child class to provide the functionality of getPrice(). The BookShelf class is a child of the Furniture class and hence provides the function body for getPrice().




Private methods cannot be abstract

If a method is defined as abstract then it cannot be declared as private (it can only be public or protected). This is because a private method cannot be inherited.

abstract class BaseClass {
 
   private abstract function myFun();
 
}
 
class DerivedClass extends BaseClass {
   public function myFun() {
	   //logic here
   }
}
 
$d = new DerivedClass(); //will cause error

What is an Interface?

An interface is a contract between unrelated objects to perform a common function. An interface enables you to specify that an object is capable of performing a certain function, but it does not necessarily tell you how the object does so, this means that it leaves for classes implementing an interface to define its behaviour.

To extend from an Interface, keyword implements is used.

We can have a class extend from more than one Interface.

 
interface Storable {
	function getContentsAsText();
}
 
class Document implements Storable {
	public function getContentsAsText() {
		return "This is Text of the Document\n";
	}
}
 
class Indexer {
	public function readAndIndex(Storable $s) {
		$textData = $s->getContentsAsText();
		//do necessary logic to index
		echo $textData;
	}
}
 
$p = new Document();
 
$i = new Indexer();
$i->readAndIndex($p);

In the above example, Document and the Indexer class are two independant classes. The Indexer class is designed to index the contents of any text. Using the Storable interface above, we declare a method getContentsAsText() in the Document class. Because the Indexer class is only concerned with the TEXT, hence we can call getContentsAsText() method on the object of Document. This way any class if it implements the method getContentsAsText() can get indexed

Difference between Abstract Class and Interface

Abstract Classes

  1. An abstract class can provide some functionality and leave the rest for derived class
  2. The derived class may or may not override the concrete functions defined in base class
  3. The child class extended from an abstract class should logically be related

Interface

  1. An interface cannot contain any functionality. It only contains definitions of the methods
  2. The derived class must provide code for all the methods defined in the interface
  3. Completely different and non-related classes can be logically be grouped together using an interface
  4. Subscribe below for article updates

Related Posts on PHP5 Tutorial – Object Oriented Programming (OOPS)

  1. PHP5 Tutorial – Learn to create a PHP5 Class
  2. PHP5 Tutorial – Learn to Create a PHP5 Class Object
  3. PHP5 Tutorial – Defining Attributes of a PHP5 Class
  4. PHP5 Tutorial – Defining Methods of a PHP5 Class
  5. PHP5 Tutorial – Creating a PHP5 Constructor __construct()
  6. PHP5 Tutorial OOPS – Creating a PHP5 Destructor __destruct()
  7. PHP5 Tutorial OOPS – PHP5 Class Access Specifiers – public, private and protected
  8. PHP5 Tutorial – $this variable explained
  9. PHP5 Tutorial – instanceOf Operator Explained
  10. PHP5 Tutorial – Defining Class Constants
  11. PHP5 Tutorial – Inheritance
  12. PHP5 Tutorial – Magic Methods – __toString() method
  13. PHP5 Tutorial – Magic Methods – __get() and __set()
  14. PHP5 Tutorial – Magic Methods – __isset() and __unset()
  15. PHP5 Tutorial – Magic Methods – __call() method
  16. PHP5 Tutorial – Magic Methods – __autoload() method
  17. PHP5 Tutorial – Magic Methods – __sleep() and __wakeup()
  18. PHP5 Tutorial – Magic Methods – __clone() method





Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/sunilb/www.sunilb.com/wp-content/themes/inove/templates/header.php:29) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/sunilb/www.sunilb.com/wp-content/themes/inove/templates/header.php:29) in /home/sunilb/www.sunilb.com/wp-content/plugins/mycaptcha/MyCaptcha.php on line 41
  1. Foobar
    April 3rd, 2008 at 12:23 | #1

    ’3. Completely different and non-related classes can be logically be grouped together using an interface’

    How is that possible? Can you explain what you mean by that?

  2. admin
    April 5th, 2008 at 10:14 | #2

    Hi,

    As regards point 3 is concerned. What I mean by it is that you can have non-related classes grouped or bound together without a direct hirerarcy.

    Take for example the Document and Indexer class. Both of them are non-related. Document stores document contents and Indexer’s class job is to Index content. This means that both of them are specialized for their own actions.

    The Storable interface makes them grouped together (not directly, but logically). Therefore, Indexer is only bothered about Indexing text content, the Document class implements a Storable method that will convert the Document data to text format so that it can be Indexed using the Indexer class.

    Hope this is clear.

    Sunil

  3. Yukti
    September 8th, 2008 at 15:39 | #3

    Thanks Sunilji for beautiful articles .

    Please explain

    “An abstract class can provide some functionality and leave the rest for derived class ”

    1) Above example
    private abstract function myFun();
    does not prove so.
    Is it that we can write some code to function. ?

    2) As a php programmer I am trying to get concepts of all that yoy have explained beautifully in all of your tutorials. All I need to understand more is ” Why and when should I use all these ? I mean intefaces abstract classes , object cloning and rest PHP 5 features” . Please suggest .

  4. admin
    November 15th, 2008 at 19:57 | #4

    Hi Yukti,

    Abstract classes and Interfaces are used in a class design to help generalize the way implementation should be done.

    Believe me – its very difficult to get you understanding of how this works.

    The best way is to study the PHP package structures or get a good open source PHP 5 code and question yourself on the logic that the author has developed.

    Let me know if you need anything more specific to ask?

    Regards,
    Suniil

  5. yukti
    November 15th, 2008 at 22:20 | #5

    Thanks for a personal response Sunilji.

    Am glad you replied. Is there any particular set of code of small php application ( a small project ) that you believe I can study?
    Or any site that I can reffer for a project code study. I searched for sample projects but got very complicated sets.

    Thanks.

  6. admin
    November 15th, 2008 at 22:55 | #6

    Hi Yukti,

    I guess its best to go through phpclasses.org.

    There are some easy and some not so easy packages waiting to be explored:)

    Let me know if you have any issues understanding a package.

    Regards,
    Suniil

  7. John
    February 6th, 2012 at 23:46 | #7

    Thanks a ton! The section on the differences between Abstract classes and interfaces really summed it up for me. The PHP website isn’t very clear that the implementation actually isn’t a class. You described it pretty elegantly here.
    Thanks for taking the time to do this!

  1. No trackbacks yet.
Enter this code to leave comment (Sorry, but bots get me crazy :) )