When to use Interfaces in PHP

回眸只為那壹抹淺笑 提交于 2019-12-10 02:08:21

问题


I have always had a hard time understanding the real value of Interfaces when coding with Objects in PHP (could be other languages I imagine)

From what I understand you use an Interface to enforce or guarantee that when a Class is using an Interface that that class will have the methods defined in the Interface inside of that class.

So from my litte knowledge of using them, wouldn't that mean you would only find an Interface beneficial when defining more then 1 class that needs those Methods?

To be more clear, if I have a class that does one thing and no other classes need to do that kind of thing, then it would be pointless to use an Interface on that class?

So you wouldn't use an Interface on EVERY class you right?

PS) If you vote this question as exact duplicate then you didn't read the question and only the title as I have read most of the similar questions already


回答1:


From what I understand you use an Interface to enforce or guarantee that when a Class is using an Interface that that class will have the methods defined in the Interface inside of that class.

This is actually only half of the deal (the technical part). There's also the all-important architectural half, which appears when you consume the interface and it goes like this:

function feed(IAnimal $interface) {
    // ...
}

(alternatively, a "factory" function that is documented to return an instance that implements IAnimal would also serve as an example).

The idea here is that the consumer of the interface says: "I want an animal to feed. I don't care if it flies, walks, or crawls. I don't care if it's big or small. I only care that it shares some features with all other animals" -- features that would comprise the definition of the interface.

In other words, interfaces serve to abstract the contract (interface) from the concrete implementation (classes). This gives implementers of concrete classes a free hand to modify, rename, remove and add implementations without breaking the code for users of the interface, something that is not possible if you are referencing concrete classes directly in your API.

As for the interface that is implemented by one class only: that's not enough information to decide. If there can plausibly be more implementations of the interface in the future, then it certainly does make sense (for example: an IHashFunction interface would make sense even if Sha1HashFunction were currently the only available implementation). Otherwise it doesn't offer anything.



来源:https://stackoverflow.com/questions/8552505/when-to-use-interfaces-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!