<p><a href="http://php.net/Interfaces" rel="noreferrer">Interfaces</a> allow you to create code which defines the methods of classes that implement it. You cannot however add any code to those methods. </p>

<p><a href="http://php.net/Abstract" rel="noreferrer">Abstract classes</a> allow you to do the same thing, along with adding code to the method. </p>

<p>Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces? </p>

<p>I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?</p>

[{'answer_id': 20470, 'author': 'John Downey', 'author_id': 200, 'author_profile': 'https://Stackoverflow.com/users/200', 'pm_score': 7, 'selected': False, 'text': '<p>The concept is useful all around in object oriented programming. To me I think of an interface as a contract. So long my class and your class agree on this method signature contract we can "interface". As for abstract classes those I see as more of base classes that stub out some methods and I need to fill in the details.</p>\n'}, {'answer_id': 20483, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 5, 'selected': False, 'text': "<p>Interfaces are essentially a blueprint for what you can create. They define what methods a class <strong>must have</strong>, but you can create extra methods outside of those limitations.</p>\n\n<p>I'm not sure what you mean by not being able to add code to methods - because you can. Are you applying the interface to an abstract class or the class that extends it? </p>\n\n<p>A method in the interface applied to the abstract class will need to be implemented in that abstract class. However apply that interface to the extending class and the method only needs implementing in the extending class. I could be wrong here - I don't use interfaces as often as I could/should.</p>\n\n<p>I've always thought of interfaces as a pattern for external developers or an extra ruleset to ensure things are correct.</p>\n"}, {'answer_id': 20485, 'author': 'Craig H', 'author_id': 2328, 'author_profile': 'https://Stackoverflow.com/users/2328', 'pm_score': 8, 'selected': True, 'text': '<p>The entire point of interfaces is to give you the flexibility to have your class be forced to implement multiple interfaces, but still not allow multiple inheritance.  The issues with inheriting from multiple classes are many and varied and the <a href="http://en.wikipedia.org/wiki/Multiple_inheritance" rel="noreferrer">wikipedia</a> page on it sums them up pretty well.</p>\n\n<p>Interfaces are a compromise.  Most of the problems with multiple inheritance don\'t apply to abstract base classes, so most modern languages these days disable multiple inheritance yet call abstract base classes interfaces and allows a class to "implement" as many of those as they want.</p>\n'}, {'answer_id': 20489, 'author': 'Henrik Paul', 'author_id': 2238, 'author_profile': 'https://Stackoverflow.com/users/2238', 'pm_score': 3, 'selected': False, 'text': "<p>In my opinion, interfaces should be preferred over non-functional abstract classes. I wouldn't be surprised if there would be even a performance hit there, as there is only one object instantiated, instead of parsing two, combining them (although, I can't be sure, I'm not familiar with the inner workings of OOP PHP).</p>\n\n<p>It is true that interfaces are less useful/meaningful than compared to, say, Java. On the other hand, PHP6 will introduce even more type hinting, including type hinting for return values. This should add some value to PHP interfaces.</p>\n\n<p>tl;dr: interfaces defines a list of methods that need to be followed (think API), while an abstract class gives some basic/common functionality, which the subclasses refine to specific needs.</p>\n"}, {'answer_id': 20500, 'author': 'Tim Frey', 'author_id': 1471, 'author_profile': 'https://Stackoverflow.com/users/1471', 'pm_score': 3, 'selected': False, 'text': '<p>Interfaces aren\'t just for making sure developers implement certain methods.  The idea is that because these classes are guaranteed to have certain methods, you can use these methods even if you don\'t know the class\'s actual type.  Example:</p>\n\n<pre><code>interface Readable {\n  String read();\n}\n\nList&lt;Readable&gt; readables; // dunno what these actually are, but we know they have read();\nfor(Readable reader : readables)\n  System.out.println(reader.read());\n</code></pre>\n\n<p>In many cases, it doesn\'t make sense to provide a base class, abstract or not, because the implementations vary wildly and don\'t share anything in common besides a few methods.</p>\n\n<p>Dynamically typed languages have the notion of "duck-typing" where you don\'t need interfaces; you are free to assume that the object has the method that you\'re calling on it.  This works around the problem in statically typed languages where your object has some method (in my example, read()), but doesn\'t implement the interface.</p>\n'}, {'answer_id': 20503, 'author': 'Ross', 'author_id': 2025, 'author_profile': 'https://Stackoverflow.com/users/2025', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>I can't remember if PHP is different in this respect, but in Java, you can implement multiple Interfaces, but you can't inherit multiple abstract classes. I'd assume PHP works the same way.</p>\n</blockquote>\n\n<p>In PHP you can apply multiple interfaces by seperating them with a comma (I think, I don't find that a clean soloution). </p>\n\n<p>As for multiple abstract classes you could have multiple abstracts extending each other (again, I'm not totally sure about that but I think I've seen that somewhere before). The only thing you can't extend is a final class.</p>\n"}, {'answer_id': 20539, 'author': 'Brian Warshaw', 'author_id': 1344, 'author_profile': 'https://Stackoverflow.com/users/1344', 'pm_score': 3, 'selected': False, 'text': "<p>Interfaces will not give your code any performance boosts or anything like that, but they can go a long way toward making it maintainable. It is true that an abstract class (or even a non-abstract class) can be used to establish an interface to your code, but proper interfaces (the ones you define with the keyword and that only contain method signatures) are just plain easier to sort through and read.</p>\n\n<p>That being said, I tend to use discretion when deciding whether or not to use an interface over a class. Sometimes I want default method implementations, or variables that will be common to all subclasses.</p>\n\n<p>Of course, the point about multiple-interface implementation is a sound one, too. If you have a class that implements multiple interfaces, you can use an object of that class as different types in the same application.</p>\n\n<p>The fact that your question is about PHP, though, makes things a bit more interesting. Typing to interfaces is still not incredibly necessary in PHP, where you can pretty much feed anything to any method, regardless of its type. You can statically type method parameters, but some of that is broken (String, I believe, causes some hiccups). Couple this with the fact that you can't type most other references, and there isn't much value in trying to force static typing in PHP (<em>at this point</em>). And because of that, the value of interfaces <em>in PHP</em>, <em>at this point</em> is far less than it is in more strongly-typed languages. They have the benefit of readability, but little else. Multiple-implementation isn't even beneficial, because you still have to declare the methods and give them bodies within the implementor.</p>\n"}, {'answer_id': 30598, 'author': 'Sam McAfee', 'author_id': 577, 'author_profile': 'https://Stackoverflow.com/users/577', 'pm_score': 5, 'selected': False, 'text': '<p>The difference between using an interface and an abstract class has more to do with code organization for me, than enforcement by the language itself. I use them a lot when preparing code for other developers to work with so that they stay within the intended design patterns. Interfaces are a kind of "design by contract" whereby your code is agreeing to respond to a prescribed set of API calls that may be coming from code you do not have aceess to.</p>\n\n<p>While inheritance from abstract class is a "is a" relation, that isn\'t always what you want, and implementing an interface is more of a "acts like a" relation. This difference can be quite significant in certain contexts.</p>\n\n<p>For example, let us say you have an abstract class Account from which many other classes extend (types of accounts and so forth). It has a particular set of methods that are only applicable to that type group. However, some of these account subclasses implement Versionable, or Listable, or Editable so that they can be thrown into controllers that expect to use those APIs. The controller does not care what type of object it is</p>\n\n<p>By contrast, I can also create an object that does not extend from Account, say a User abstract class, and still implement Listable and Editable, but not Versionable, which doesn\'t make sense here.</p>\n\n<p>In this way, I am saying that FooUser subclass is NOT an account, but DOES act like an Editable object. Likewise BarAccount extends from Account, but is not a User subclass, but implements Editable, Listable and also Versionable.</p>\n\n<p>Adding all of these APIs for Editable, Listable and Versionable into the abstract classes itself would not only be cluttered and ugly, but would either duplicate the common interfaces in Account and User, or force my User object to implement Versionable, probably just to throw an exception.</p>\n'}, {'answer_id': 14778904, 'author': 'catalin.costache', 'author_id': 275944, 'author_profile': 'https://Stackoverflow.com/users/275944', 'pm_score': 4, 'selected': False, 'text': "<p>You will use interfaces in PHP:</p>\n\n<p><ol>\n<li>To hide implementation - establish an access protocol to a class of objects an change the underlying implementation without refactoring in all the places you've used that objects</li>\n<li>To check type - as in making sure that a parameter has a specific type <code>$object instanceof MyInterface</code></li>\n<li>To enforce parameter checking at runtime</li>\n<li>To implement multiple behaviours into a single class (build complex types)</p>\n\n<blockquote>\n  <p>class Car implements EngineInterface, BodyInterface, SteeringInterface {</li>\n  </ol>\n  so that a <code>Car</code> object ca now <code>start()</code>, <code>stop()</code> (EngineInterface) or <code>goRight()</code>,<code>goLeft()</code> (Steering interface)</p>\n</blockquote>\n\n<p>and other things I cannot think of right now</p>\n\n<p>Number 4 it's probably the most obvious use case that you cannot address with abstract classes.</p>\n\n<p>From Thinking in Java:</p>\n\n<blockquote>\n  <p>An interface says, “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods can be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes.</p>\n</blockquote>\n"}, {'answer_id': 24436493, 'author': 'Jo Smo', 'author_id': 1286942, 'author_profile': 'https://Stackoverflow.com/users/1286942', 'pm_score': 6, 'selected': False, 'text': '<p><strong>Why would you need an interface, if there are already abstract classes?</strong>\nTo prevent multiple inheritance (can cause multiple known problems).</p>\n\n<p>One of such problems:</p>\n\n<blockquote>\n  <p>The "diamond problem" (sometimes referred to as the "deadly diamond of\n  death") is an ambiguity that arises when two classes B and C inherit\n  from A and class D inherits from both B and C. If there is a method\n  in A that B and C have overridden, and D does not override it, then\n  which version of the method does D inherit: that of B, or that of C?</p>\n</blockquote>\n\n<p>Source: <a href="https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem" rel="noreferrer">https://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem</a></p>\n\n<p><strong>Why/When to use an interface?</strong>\nAn example... All cars in the world have the same interface (methods)... <code>AccelerationPedalIsOnTheRight()</code>, <code>BrakePedalISOnTheLeft()</code>. Imagine that each car brand would have these "methods" different from another brand. BMW would have The brakes on the right side, and Honda would have brakes on the left side of the wheel. People would have to learn how these "methods" work every time they would buy a different brand of car. That\'s why it\'s a good idea to have the same interface in multiple "places."</p>\n\n<p>What does an interface do for you (why would someone even use one)?\nAn interface prevents you from making "mistakes" (it assures you that all classes which implement a specific interface, will all have the methods which are in the interface).</p>\n\n<pre><code>// Methods inside this interface must be implemented in all classes which implement this interface.\ninterface IPersonService\n{   \n    public function Create($personObject);\n}\n\nclass MySqlPerson implements IPersonService\n{\n    public function Create($personObject)\n    {\n        // Create a new person in MySql database.\n    }\n}\n\nclass MongoPerson implements IPersonService\n{\n    public function Create($personObject)\n    {\n        // Mongo database creates a new person differently then MySQL does. But the code outside of this method doesn\'t care how a person will be added to the database, all it has to know is that the method Create() has 1 parameter (the person object).\n    }\n}\n</code></pre>\n\n<p>This way, the <code>Create()</code> method will always be used the same way. It doesn\'t matter if we are using the <code>MySqlPerson</code> class or the <code>MongoPerson</code> class. The way how we are using a method stays the same (the interface stays the same).</p>\n\n<p>For example, it will be used like this (everywhere in our code):</p>\n\n<pre><code>new MySqlPerson()-&gt;Create($personObject);\nnew MongoPerson()-&gt;Create($personObject);\n</code></pre>\n\n<p>This way, something like this can\'t happen:</p>\n\n<pre><code>new MySqlPerson()-&gt;Create($personObject)\nnew MongoPerson()-&gt;Create($personsName, $personsAge);\n</code></pre>\n\n<p>It\'s much easier to remember one interface and use the same one everywhere, than multiple different ones.</p>\n\n<p>This way, the inside of the <code>Create()</code> method can be different for different classes, without affecting the "outside" code, which calls this method. All the outside code has to know is that the method <code>Create()</code> has 1 parameter (<code>$personObject</code>), because that\'s how the outside code will use/call the method. The outside code doesn\'t care what\'s happening inside the method; it only has to know how to use/call it.</p>\n\n<p>You can do this without an interface as well, but if you use an interface, it\'s "safer" (because it prevents you to make mistakes). The interface assures you that the method <code>Create()</code> will have the same signature (same types and a same number of parameters) in all classes that implement the interface. This way you can be sure that ANY class which implements the <code>IPersonService</code> interface, will have the method <code>Create()</code> (in this example) and will need only 1 parameter (<code>$personObject</code>) to get called/used.</p>\n\n<p>A class that implements an interface must implement all methods, which the interface does/has.</p>\n\n<p>I hope that I didn\'t repeat myself too much.</p>\n'}, {'answer_id': 31732368, 'author': 'Houghtelin', 'author_id': 2625390, 'author_profile': 'https://Stackoverflow.com/users/2625390', 'pm_score': 4, 'selected': False, 'text': "<p>Interfaces exist not as a base on which classes can extend but as a map of required functions.  </p>\n\n<p>The following is an example of using an interface where an abstract class does not fit:<br>\nLets say I have a calendar application that allows users to import calendar data from external sources.  I would write classes to handle importing each type of data source (ical, rss, atom, json) Each of those classes would implement a common interface that would ensure they all have the common public methods that my application needs to get the data. </p>\n\n<pre><code>&lt;?php\n\ninterface ImportableFeed \n{\n    public function getEvents();\n}\n</code></pre>\n\n<p>Then when a user adds a new feed I can identify the type of feed it is and use the class developed for that type to import the data.   Each class written to import data for a specific feed would have completely different code, there may otherwise be very few similarities between the classes outside of the fact that they are required to implement the interface that allows my application to consume them. If I were to use an abstract class, I could very easily ignore the fact that I have not overridden the getEvents() method which would then break my application in this instance whereas using an interface would not let my app run if ANY of the methods defined in the interface do not exist in the class that implemented it. My app doesn't have to care what class it uses to get data from a feed, only that the methods it needs to get that data are present.</p>\n\n<p>To take this a step further, the interface proves to be extremely useful when I come back to my calendar app with the intent of adding another feed type. Using the ImportableFeed interface means I can continue adding more classes that import different feed types by simply adding new classes that implement this interface.  This allows me to add tons of functionality without having to add unnecessarily bulk to my core application since my core application only relies on there being the public methods available that the interface requires so as long as my new feed import classes implement the ImportableFeed interface then I know I can just drop it in place and keep moving.</p>\n\n<p>This is just a very simple start. I can then create another interface that all my calendar classes can be required to implement that offers more functionality specific to the feed type the class handles. Another good example would be a method to verify the feed type, etc.</p>\n\n<p>This goes beyond the question but since I used the example above:\nInterfaces come with their own set of issues if used in this manner.  I find myself needing to ensure the output that is returned from the methods implemented to match the interface and to achieve this I use an IDE that reads PHPDoc blocks and add the return type as a type hint in a PHPDoc block of the interface which will then translate to the concrete class that implements it.  My classes that consume the data output from the classes that implement this interface will then at the very least know it's expecting an array returned in this example:</p>\n\n<pre><code>&lt;?php\ninterface ImportableFeed \n{\n    /**\n     * @return array\n     */\n    public function getEvents();\n}\n</code></pre>\n\n<p>There isn't much room in which to compare abstract classes and interfaces.  Interfaces are simply maps that when implemented require the class to have a set of public interfaces.</p>\n"}, {'answer_id': 41606650, 'author': 'vivek s vamja', 'author_id': 2459995, 'author_profile': 'https://Stackoverflow.com/users/2459995', 'pm_score': 2, 'selected': False, 'text': '<p>Below are the points for PHP Interface </p>\n\n<ol>\n<li>It is used to define required no of methods in class [if you want to load html then id and name is required so in this case interface include setID and setName].</li>\n<li>Interface strictly force class to include all the methods define in it. </li>\n<li>You can only define method in interface with public accessibility.</li>\n<li>You can also extend interface like class. You can extend interface in php using extends keyword.</li>\n<li>Extend multiple interface.</li>\n<li>You can not implement 2 interfaces if both share function with same name. It will throw error.</li>\n</ol>\n\n<p><strong>Example code :</strong></p>\n\n<pre><code>interface test{\n    public function A($i);\n    public function B($j = 20);\n}\n\nclass xyz implements test{\n    public function A($a){\n        echo "CLASS A Value is ".$a;\n    }\n    public function B($b){\n        echo "CLASS B Value is ".$b;\n    }\n}\n$x = new xyz();\necho $x-&gt;A(11);\necho "&lt;br/&gt;";\necho $x-&gt;B(10);\n</code></pre>\n'}, {'answer_id': 48825610, 'author': 'Hiren Gohel', 'author_id': 6000629, 'author_profile': 'https://Stackoverflow.com/users/6000629', 'pm_score': 2, 'selected': False, 'text': '<p>We saw that abstract classes and interfaces are similar in that they provide abstract methods that must be implemented in the child classes. However, they still have the following differences:</p>\n\n<blockquote>\n  <p>1.Interfaces can include abstract methods and constants, but cannot contain concrete methods and variables.</p>\n  \n  <p>2.All the methods in the interface must be in the <strong>public</strong> visibility\n  scope.</p>\n  \n  <p>3.A class can implement more than one interface, while it can inherit\n  from only one abstract class.</p>\n</blockquote>\n\n<pre><code>                                  interface                      abstract class\nthe code                     - abstract methods               - abstract methods\n                             - constants                      - constants                  \n                                                              - concrete methods\n                                                              - concrete variables\n\naccess modifiers             \n                             - public                         - public\n                                                              - protected\n                                                              - private\n                                                                etc.\nnumber of parents          The same class can implement\n                           more than 1 interface              The child class can \n                                                              inherit only from 1 abstract class\n</code></pre>\n\n<p>Hope this will helps to anyone to understand!</p>\n'}, {'answer_id': 52538843, 'author': 'Tapha', 'author_id': 276809, 'author_profile': 'https://Stackoverflow.com/users/276809', 'pm_score': 2, 'selected': False, 'text': '<p>Interfaces are like your genes.</p>\n\n<p>Abstract classes are like your actual parents.</p>\n\n<p>Their purposes are hereditary, but in the case of abstract classes vs interfaces, what is inherited is more specific.</p>\n'}, {'answer_id': 55528833, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>I don't know about other languages, what is the concept of interface there. But for PHP, I will try my best to explain it. Just be patient, and Please comment if this helped.</p>\n<blockquote>\n<p>An interface works as a &quot;contracts&quot;, specifying what a set of subclasses does, but not how they do it.</p>\n</blockquote>\n<p><strong>The Rule</strong></p>\n<blockquote>\n<ol>\n<li><p>An Interface can't be instantiate.</p>\n</li>\n<li><p>You can't implement any method in an interface,i.e. it only contains .signature of the method but not details(body).</p>\n</li>\n<li><p>Interfaces can contain methods and/or constants, but no attributes. Interface constants have the same restrictions as class constants. Interface methods are implicitly abstract.</p>\n</li>\n<li><p>Interfaces must not declare constructors or destructors, since these are implementation details on the class\nlevel.</p>\n</li>\n<li><p>All the methods in an interface must have public visibility.</p>\n</li>\n</ol>\n</blockquote>\n<p>Now let's take an example.\nSuppose we have two toys: one is a Dog, and other one is a Cat.</p>\n<p>As we know a dog barks, and cat mews.These two have same speak method, but with different functionality or implementation.\nSuppose we are giving the user a remote control that has a speak button.</p>\n<blockquote>\n<p>When the user presses speak button, the toy have to speak it doesn't matter if it's Dog or a Cat.</p>\n</blockquote>\n<p><strong>This a good case to use an interface, not an abstract class because the implementations are different.\nWhy? Remember</strong></p>\n<p><strong>If you need to support the child classes by adding some non-abstract method, you should use abstract classes. Otherwise, interfaces would be your choice.</strong></p>\n"}]
['https://Stackoverflow.com/questions/20463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1797/']