-3

What if I don't use interfaces in PHP OOP? They are just declaration of function, no implementation at all! Say I don't use interface, then what would happen?

I am somehow unable to get the use of it in PHP.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Sigh... someday you will know how _badly_ we need interface in our daily life too. – mazhar islam Jul 26 '15 at 18:17
  • Please I need explanation , i wasted already 10 hours of mine. – 0____________0 Jul 26 '15 at 18:17
  • 5
    If you don't use interfaces, your code will cause the server to overheat, triggering a nuclear explosion that will wipe out your hosting providers server farm, taking down half of the internet and destroying the entire city, rendering it radio-active and uninhabitable for the next 10,000 years – Mark Baker Jul 26 '15 at 18:19
  • possible duplicate of [What is the point of interfaces in PHP?](http://stackoverflow.com/questions/20463/what-is-the-point-of-interfaces-in-php) – cbr Jul 26 '15 at 18:20
  • 3
    You got downvotes because you are asking an answered question. You don't **have to** use interfaces. An interface is a contract. In a world where a lot of code talks to other code, we have to set some rules. Interfaces help us set those rules. – N.B. Jul 26 '15 at 18:20
  • No, interfaces aren't mandatory - interfaces are a tool for enforcing a structural definition of classes, commonly used in libraries, frameworks, etc; but in no way essential to code, just good practise – Mark Baker Jul 26 '15 at 18:21
  • ok so its just for good practice. Because i saw it just has function definition without any body , so i thought they are not usful. – 0____________0 Jul 26 '15 at 18:25
  • 1
    Perhaps slightly more than just good practise, because you can also type-hint to an interface, although even type hinting isn't mandatory in PHP – Mark Baker Jul 26 '15 at 18:36
  • 1
    @halfer - noted, no problem. – N.B. Jul 26 '15 at 18:57

1 Answers1

3

Suppose there are many kind of Keys, say AES, DES, RSA, EC etc. They have so many different properties with some common properties too!

So you declare classes named AES, DES etc. As they have common properties, (say getKeyValue(), setKeyValue()) so your every Key class has these two methods in common.

Now you are going to implement something (say a function which prepare a Key and return it) where you don't know which Key will come to you (or which key you are going to return).

So how you going to handle this thing? Declare all these Key objects to receive the unknown Key? Like the following?

AES aes = ...
DES des = ...
. 
.
.
EC ec = ... 

What if you just do the following?

Key key = ... // this key object can hold all the keys

So easy, aha? That Key is an interface where every Key (AES, DES bla bla) implements it!

mazhar islam
  • 5,561
  • 3
  • 20
  • 41