40

I'm looking for an answer to question which is not difficult, but I can't find out how many interfaces can be implemented by one class.

Is this possible?

class Class1 implements Interface1, Interface2, Interface3, Interface4 {
   .....
}

For all the similar examples I found, I've seen that there can be only 2 interfaces implemented by one class. But there isn't any info about what I'm looking for.

MacMac
  • 34,294
  • 55
  • 151
  • 222
Arnas Pečelis
  • 1,000
  • 2
  • 12
  • 32

5 Answers5

48

There is no limit on the number of interfaces that you can implement. By definition, you can only extend (inherit) one class.

I would, as a practical matter, limit the number of Interfaces you do implement, lest your class become overly bulky and thus hard to work with.

Machavity
  • 30,841
  • 27
  • 92
  • 100
15

You can implement as many class you want, there is no limitation in that.

class Class1 implements Interface1, Interface2, Interface3, Interface4, Interface5, Interface6{
   .....
} 

This means this is right Hope this helps you

Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38
7

I wrote a script that proves the answer that the amount is not limited:

<?php

$inters_string = '';

$interfaces_to_generate = 9999;

for($i=0; $i <= $interfaces_to_generate; $i++) {
  $cur_inter = 'inter'.$i;
  $inters[] = $cur_inter;
  $inters_string .= sprintf('interface %s {} ', $cur_inter);
}

eval($inters_string); // creates all the interfaces due the eval (executing a string as code)

eval(sprintf('class Bar implements %s {}', implode(',',$inters))); // generates the class that implements all that interfaces which were created before

$quxx = new Bar();

print_r(class_implements($quxx));

You can modify the counter var in the for loop to make that script generate even more interfaces to be implemented by the class "Bar".

It easily works with up to 9999 interfaces (and obviously more) as you can see from the output of the last code line (print_r) when executing that script.

The computer's memory seems to be the only limitation for the amount of interfaces for you get an memory exhausted error when the number is too high

Ryan M
  • 18,333
  • 31
  • 67
  • 74
serjoscha
  • 510
  • 4
  • 10
7

Yes, more than two interfaces can be implemented by a single class.
From the PHP manual:

Classes may implement more than one interface if desired by separating each interface with a comma.

0x5C91
  • 3,360
  • 3
  • 31
  • 46
1

The number of interfaces a class can implement is not logically limited.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266