Search code examples
phpinterface

How to create an interface composed of other interfaces?


I'd like to create an interface, IFoo, that's basically a combination of a custom interface, IBar, and a few native interfaces, ArrayAccess, IteratorAggregate, and Serializable. PHP doesn't seem to allow interfaces that implement other interfaces, as I get the following error when I try:

PHP Parse error: syntax error, unexpected T_IMPLEMENTS, expecting '{' in X on line Y

I know that interfaces can extend other ones, but PHP doesn't allow multiple inheritance and I can't modify native interfaces, so now I'm stuck.

Do I have to duplicate the other interfaces within IFoo, or is there a better way that allows me to reuse the native ones?


Solution

  • You are looking for the extends keyword:

    Interface Foo extends Bar, ArrayAccess, IteratorAggregate, Serializable
    {
        ...
    }
    

    See Object Interfaces and in specific Example #2 Extendable Interfaces ff.


    Note: Just removed the I prefix in the IFoo, IBar interface names.

    For an additional perspective of a PHP developer I can recommend the reading of "Prefixes and Suffixes Do Not Belong in Interface Names" by David Grudl for Nette (Jun 2022).