Interfaces
A class can implement a set of capabilities — herein called a contract — through what is called an interface. An interface is a set of method declarations and constants. Note that the methods are only declared, not defined; that is, an interface defines a type consisting of abstract methods, where those methods are implemented by client classes as they see fit. An interface allows unrelated classes to implement the same facilities with the same names and types without requiring those classes to share a common base class.
An interface can extend one or more other interfaces, in which case, it inherits all members from its base interface(s).
Interface Declarations
interface-declaration: interface name interface-base-clauseopt < interface-member-declarationsopt > interface-base-clause: extends qualified-name interface-base-clause , qualified-name
Constraints
An interface must not be derived directly or indirectly from itself.
Every qualified-name must name an interface type.
An interface-declaration defines a contract that one or more classes can implement.
Interface names are case-insensitive.
The optional interface-base-clause specifies the base interfaces from which the interface being defined is derived. In such a case, the derived interface inherits all the members from the base interfaces.
interface MyCollection < const MAX_NUMBER_ITEMS = 1000; function put($item); function get(); >class MyList implements MyCollection < public function put($item) < /* implement method */ >public function get() < /* implement method */ >. > class MyQueue implements MyCollection < public function put($item) < /* implement method */ >public function get() < /* implement method */ >. > function processCollection(MyCollection $p1) < . /* can process any object whose class implements MyCollection */ >processCollection(new MyList(. )); processCollection(new MyQueue(. ));
Interface Members
interface-member-declarations: interface-member-declaration interface-member-declarations interface-member-declaration interface-member-declaration: class-const-declaration method-declaration
The members of an interface are those specified by its interface-member-declaration, and the members inherited from its base interfaces.
An interface may contain the following members:
- Constants – the constant values associated with the interface.
- Methods – placeholders for the computations and actions that can be performed by implementers of the interface.
Constants
Constraints
All constants declared in an interface must be implicitly or explicitly public.
An interface constant is just like a class constant, except that an interface constant cannot be overridden by a class that implements it nor by an interface that extends it.
Methods
Constraints
All methods declared in an interface must be implicitly or explicitly public, and they must not be declared abstract .
An interface method is just like an abstract method.
Predefined Interfaces
Interface ArrayAccess
This interface allows an instance of an implementing class to be accessed using array-like notation. This interface is defined, as follows:
The interface members are defined below:
Name | Purpose |
---|---|
offsetExists | This instance method returns TRUE if the instance contains an element with key $offset , otherwise, FALSE . |
offsetGet | This instance method gets the value having key $offset . It may return by value or byRef. (Ordinarily, this wouldn’t be allowed because a class implementing an interface needs to match the interface’s method signatures; however, the Engine gives special treatment to ArrayAccess and allows this). This method is called when an instance of a class that implements this interface is subscripted in a non-lvalue context. |
offsetSet | This instance method sets the value having key $offset to $value. It returns no value. This method is called when an instance of a class that implements this interface is subscripted in a modifiable-lvalue context. |
offsetUnset | This instance method unsets the value having key $offset . It returns no value. |
Interface Iterator
This interface allows instances of an implementing class to be treated as a collection. This interface is defined, as follows:
interface Iterator extends Traversable
The interface members are defined below:
Name | Purpose |
---|---|
current | This instance method returns the element at the current position. |
key | This instance method returns the key of the current element. On failure, it returns NULL ; otherwise, it returns the scalar value of the key. |
next | This instance method moves the current position forward to the next element. It returns no value. From within a foreach statement, this method is called after each loop. |
rewind | This instance method resets the current position to the first element. It returns no value. From within a foreach statement, this method is called once, at the beginning. |
valid | This instance method checks if the current position is valid. It takes no arguments. It returns a bool value of TRUE to indicate the current position is valid; FALSE , otherwise. This method is called after each call to Iterator::rewind() and Iterator::next() . |
Interface IteratorAggregate
This interface allows the creation of an external iterator. This interface is defined, as follows:
interface IteratorAggregate extends Traversable
The interface members are defined below:
Name | Purpose |
---|---|
getIterator | This instance method retrieves an iterator, which implements Iterator or Traversable . It throws an Exception on failure. |
Interface Throwable
This type is the base interface for the type of any object that can be thrown via a throw statement. A user-written class cannot implement Throwable directly. Instead, it must extend Error or Exception .
This type is defined, as follows:
The interface members are defined below:
Name | Purpose |
---|---|
__toString | string ; retrieves a string representation of the exception in some unspecified format |
getCode | int ; retrieves the exception code |
getFile | string ; retrieves the name of the script where the exception was generated |
getLine | int ; retrieves the source line number in the script where the exception was generated |
getMessage | string ; retrieves the exception message |
getPrevious | Throwable ; retrieves the previous exception, if one exists; otherwise returns NULL |
getTrace | array ; retrieves the function stack trace information as an array |
getTraceAsString | string ; retrieves the function stack trace information formatted as a single string in some unspecified format |
Interface Traversable
This interface is intended as the base interface for all traversable classes. This interface is defined, as follows:
This interface has no members.
Interface Serializable
This interface provides support for custom serialization. It is defined, as follows:
The interface members are defined below:
Name | Purpose |
---|---|
serialize | This instance method returns a string representation of the current instance. On failure, it returns NULL . |
unserialize | This instance method constructs an object from its string form designated by $serialized . It does not return a value. |
Php call interface function
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are implemented. Interfaces share a namespace with classes and traits, so they may not use the same name.
Interfaces are defined in the same way as a class, but with the interface keyword replacing the class keyword and without any of the methods having their contents defined.
All methods declared in an interface must be public; this is the nature of an interface.
In practice, interfaces serve two complementary purposes:
- To allow developers to create objects of different classes that may be used interchangeably because they implement the same interface or interfaces. A common example is multiple database access services, multiple payment gateways, or different caching strategies. Different implementations may be swapped out without requiring any changes to the code that uses them.
- To allow a function or method to accept and operate on a parameter that conforms to an interface, while not caring what else the object may do or how it is implemented. These interfaces are often named like Iterable , Cacheable , Renderable , or so on to describe the significance of the behavior.
Interfaces may define magic methods to require implementing classes to implement those methods.
Note:
Although they are supported, including constructors in interfaces is strongly discouraged. Doing so significantly reduces the flexibility of the object implementing the interface. Additionally, constructors are not enforced by inheritance rules, which can cause inconsistent and unexpected behavior.
implements
To implement an interface, the implements operator is used. All methods in the interface must be implemented within a class; failure to do so will result in a fatal error. Classes may implement more than one interface if desired by separating each interface with a comma.
A class that implements an interface may use a different name for its parameters than the interface. However, as of PHP 8.0 the language supports named arguments, which means callers may rely on the parameter name in the interface. For that reason, it is strongly recommended that developers use the same parameter names as the interface being implemented.
Note:
Interfaces can be extended like classes using the extends operator.
Note:
The class implementing the interface must declare all methods in the interface with a compatible signature. A class can implement multiple interfaces which declare a method with the same name. In this case, the implementation must follow the signature compatibility rules for all the interfaces. So covariance and contravariance can be applied.
Constants
It’s possible for interfaces to have constants. Interface constants work exactly like class constants. Prior to PHP 8.1.0, they cannot be overridden by a class/interface that inherits them.
Examples
Example #1 Interface example
// Declare the interface ‘Template’
interface Template
public function setVariable ( $name , $var );
public function getHtml ( $template );
>
// Implement the interface
// This will work
class WorkingTemplate implements Template
private $vars = [];
public function setVariable ( $name , $var )
$this -> vars [ $name ] = $var ;
>
public function getHtml ( $template )
foreach( $this -> vars as $name => $value ) $template = str_replace ( » , $value , $template );
>
// This will not work
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (Template::getHtml)
class BadTemplate implements Template
private $vars = [];
public function setVariable ( $name , $var )
$this -> vars [ $name ] = $var ;
>
>
?>
Example #2 Extendable Interfaces
interface B extends A
public function baz ( Baz $baz );
>
// This will work
class C implements B
public function foo ()
>
public function baz ( Baz $baz )
>
>
// This will not work and result in a fatal error
class D implements B
public function foo ()
>
Example #3 Variance compatibility with multiple interfaces
class Foo <>
class Bar extends Foo <>
?php
interface A public function myfunc ( Foo $arg ): Foo ;
>
interface B public function myfunc ( Bar $arg ): Bar ;
>
class MyClass implements A , B
public function myfunc ( Foo $arg ): Bar
return new Bar ();
>
>
?>
Example #4 Multiple interface inheritance
interface B
public function bar ();
>
interface C extends A , B
public function baz ();
>
class D implements C
public function foo ()
>
Example #5 Interfaces with constants
// Prints: Interface constant
echo A :: B ;
class B implements A
const B = ‘Class constant’ ;
>
// Prints: Class constant
// Prior to PHP 8.1.0, this will however not work because it was not
// allowed to override constants.
echo B :: B ;
?>
Example #6 Interfaces with abstract classes
interface A
public function foo ( string $s ): string ;
?php
public function bar ( int $i ): int ;
>
// An abstract class may implement only a portion of an interface.
// Classes that extend the abstract class must implement the rest.
abstract class B implements A
public function foo ( string $s ): string
return $s . PHP_EOL ;
>
>
class C extends B
public function bar ( int $i ): int
return $i * 2 ;
>
>
?>
Example #7 Extending and implementing simultaneously
// The keyword order here is important. ‘extends’ must come first.
class Two extends One implements Usable , Updatable
/* . */
>
?>
An interface, together with type declarations, provides a good way to make sure that a particular object contains particular methods. See instanceof operator and type declarations.