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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.