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