5

Possible Duplicates:
purpose of interface in classes
What is the difference between an interface and abstract class?

Hi I am a php programmer. any body can explain what is the advantage of using interface and abstract class.

Community
  • 1
  • 1
DEVOPS
  • 18,190
  • 34
  • 95
  • 118
  • Reference: http://www.php.net/manual/en/language.oop5.interfaces.php – Pekka Jan 05 '11 at 17:25
  • 1
    A possible duplicate of http://stackoverflow.com/questions/1913098/php-what-is-the-difference-between-an-interface-and-abstract-class – Saul Jan 05 '11 at 17:26
  • 1
    ... or any other of the millions of resources on it (note that language-agnostic resources should mostly apply here, too, so you can avoid the sometimes scaringly low-quality PHP examples). –  Jan 05 '11 at 17:26
  • 1
    You should begin to read all of these questions: http://stackoverflow.com/search?q=abstract+interface – Luc M Jan 05 '11 at 17:27
  • See also [What is the point of interfaces in a weakly-typed language like PHP?](http://stackoverflow.com/questions/2758254/what-is-the-point-of-interfaces-in-a-weakly-typed-language-like-php) – Pekka Jan 05 '11 at 17:27

1 Answers1

15

The main advantage of an interface is that it allows you to define a protocol to be implemented for an object to have some behavior. For example, you could have a Comparable interface with a compare method for classes to implement, and every class that implements it would have a standardized method for comparison.

Abstract classes allow you to define a common base for several concrete classes. For example, let's say you wanted to define classes representing animals:

abstract class Animal {
    abstract protected function eat();
    abstract protected function sleep();
    public function die() {
        // Do something to indicate dying
    }
}

In this case, we define eat() and sleep() as abstract because different types of animals (e.g. lion, bear, etc.) that will inherit from Animal eat and sleep in different ways. But all animals die the same way (don't hold me to that), so we can define a common function for that. Using an abstract class helped us 1.) declare some common methods that all Animals should have, and 2.) define common behavior for Animals. So, when you extend Animal, you won't have to rewrite the code for die().

Rafe Kettler
  • 75,757
  • 21
  • 156
  • 151