How to create an interface composed of other interfaces?

PhpInterface

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

You are looking for the extends keyword:

Interface IFoo extends IBar, ArrayAccess, IteratorAggregate, Serializable
{
    ...
}

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

Solution 2 - Php

You need to use the extends keyword to extend your interface and when you need to implement the interface in your class then you need to use the implements keyword to implement it.

You can use implements over multiple interfaces in you class. If you implement the interface then you need to define the body of all functions, like this...

interface FirstInterface
{
	function firstInterfaceMethod1();
	function firstInterfaceMethod2();
}
interface SecondInterface
{
	function SecondInterfaceMethod1();
	function SecondInterfaceMethod2();
}
interface PerantInterface extends FirstInterface, SecondInterface
{
	function perantInterfaceMethod1();
	function perantInterfaceMethod2();
}


class Home implements PerantInterface
{
	function firstInterfaceMethod1()
	{
		echo "firstInterfaceMethod1 implement";
	}

	function firstInterfaceMethod2()
	{
		echo "firstInterfaceMethod2 implement";
	}
	function SecondInterfaceMethod1()
	{
		echo "SecondInterfaceMethod1 implement";
	}
	function SecondInterfaceMethod2()
	{
		echo "SecondInterfaceMethod2 implement";
	}
	function perantInterfaceMethod1()
	{
		echo "perantInterfaceMethod1 implement";
	}
	function perantInterfaceMethod2()
	{
		echo "perantInterfaceMethod2 implement";
	}
}
    
$obj = new Home();
$obj->firstInterfaceMethod1();

and so on... call methods

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFtDRbwLXw6View Question on Stackoverflow
Solution 1 - PhphakreView Answer on Stackoverflow
Solution 2 - Phpfurkanali89View Answer on Stackoverflow