Jump to content

PHP abstract vs interface?


chantown

Recommended Posts

From what i understand, you use an abstract class when you want to create subclasses which share a common set of functions AND variables.  For instance you have an abstract class Animal with variables which help define ANY animal, such as hunger, happiness, etc..  When you extend it with a class such as Dog, the Dog has all the variables and functions any Animal would have; it would still have happiness and hunger. However, you then can declare your own variables which only a Dog would have such as breed.  On the other hand with an interface you only define a set of functions that will be included in a class.

An interface defines an interface. An abstract class defines an interface, but can also define common behaviour for it's decendants.

 

Inheritance (using 'extends') is a 'generalization', implementing an interface is an 'realization'. This only emphasizes the fact that interfaces do not define behaviour, only suggests a certain quality. The difference is sometimes marginal, and indeed you can often use an abstract class instead of an interface.

 

However, a class can implement a multitude of interfaces, which can be used as a signal to client code that the object can be used in certain way.

 

For example, an object may implement the interface Serializable, which is a signal to client code that the object can be used with serialization.

 

Hope that helps.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.