How many interfaces can a class implement in PHP?

31,548

Solution 1

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.

Solution 2

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

Solution 3

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.

Solution 4

I wrote a script that proofs above statements (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

Share:
31,548
Arnas Pečelis
Author by

Arnas Pečelis

I'm a simple back-end developer who loves to have headache. Most hated part of programming is recursions. Especially those, who could be unlimited until you reach the end and see how hard it was. That's all.

Updated on February 12, 2020

Comments

  • Arnas Pečelis
    Arnas Pečelis about 4 years

    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.