What is the real usefulness of Interface in PHP?

3

I know that interface is used as a common standard. But I do not think it's useful. So what's the use of creating an interface that knows its name?

I have to code each of them in the class that is implementing the interface. What is the gain?

    
asked by anonymous 01.09.2018 / 13:00

2 answers

6

In PHP? It really does not have much advantage, but it's changing with a metamorphosis of the language.

If you're programming how PHP was designed really does not make sense because interface is a contract engine where you say what methods one has and then you create types that conform to it, and in your code you can say that some place accepts an interface and then any object that implements the interface can be used there because it meets the requirement.

It is a way for you to give a name to an operation that an object can do, and then you can say that it accepts objects that know how to do the operation. So it's a mechanism to ensure robustness, give type security.

But PHP is a dynamic typing language, and it does not make sense to ask for type security in such a language. PHP is a script language and should not have to deal with this kind of complexity.

It's true that PHP realized that this is not very good and is changing the philosophy, but you can not sort everything out for compatibility, so it's a hybrid thing and it has the worst of both worlds (part of the best too, of course , but partial does not help that much).

Want type security? Great, use in a static typing language that forces this to occur in all cases. Do you like PHP? Use Hack . If not think of Java, C #, these things.

Do not mind type security? Okay, if it really does script it is not that much needed, but then it gets weird to use interface.

If you understand everything you are doing in the code you will see that much of what you preach today in PHP does not make sense. People use it without question. I'm glad you asked.

See more at:

01.09.2018 / 21:01
-2

I thought the same way, but the interface avoids code repetition when you have different behaviors from the same object types.

Imagine that you are using the Mysql database and you have a Connection class. This class makes a direct connection to Mysql.

Now imagine that all of your persistence layer has the Connection class and a new client has arrived which will require a new database and you will now use two databases.

So you need to change your code to support the new bank and ensure support for the previous bank. That is, in some places it will be the Mysql Connection and in the other Connection of a new bank.

To avoid two Connections doing the same thing, you create a Connection interface and the ConnectionMysql and ConnectionPostgree classes will implement it.

Now your code can use the Connection interface instead of the ConnectionMysql or ConnectionPostgree classes.

    
01.09.2018 / 19:01