How many interfaces can a class implement in PHP?

I am looking for an answer to a question that is not difficult, but I can’t find out how many interfaces can be implemented by one class.

Is it possible?

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

For all the similar examples that I found, I saw that there can only be two interfaces for one class. But there is no information about what I am looking for.

+6
source share
5 answers

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

For practical reasons, I would limit the number of interfaces that you implement so that your class does not become excessively cumbersome and, therefore, is difficult to work with.

+15
source

I wrote a script that proves the above statements (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 change the var counter in a for loop to make the script create even more interfaces that will be implemented by the "Bar" class.

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

Computer memory seems to be the only limit on the number of interfaces for which you get an exhausted memory error when the number is too large.

+3
source

Yes, more than two interfaces can be implemented in one class.
From the PHP manual:

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

+3
source

The number of interfaces that a class can implement is logically unlimited.

0
source

You can implement as many classes as you want, there are no restrictions.

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

That means it's right. Hope this helps you.

0
source

Source: https://habr.com/ru/post/982325/


All Articles