What is use of interface class in php?


PHP - What are Interfaces?

Interfaces allow you to specify what methods a class should implement.

Interfaces make it easy to use a variety of different classes in the same way. When one or more classes use the same interface, it is referred to as "polymorphism".

Interfaces are declared with the interface keyword:

Syntax

interface InterfaceName {
  public function someMethod1();
  public function someMethod2($name, $color);
  public function someMethod3() : string;
}
?>


PHP - Interfaces vs. Abstract Classes

Interface are similar to abstract classes. The difference between interfaces and abstract classes are:

  • Interfaces cannot have properties, while abstract classes can
  • All interface methods must be public, while abstract class methods is public or protected
  • All methods in an interface are abstract, so they cannot be implemented in code and the abstract keyword is not necessary
  • Classes can implement an interface while inheriting from another class at the same time

PHP - Using Interfaces

To implement an interface, a class must use the implements keyword.

A class that implements an interface must implement all of the interface's methods.

Example

interface Animal {
  public function makeSound();
}

class Cat implements Animal {
  public function makeSound() {
    echo "Meow";
  }
}

$animal = new Cat();
$animal->makeSound();
?>

Try it Yourself »

From the example above, let's say that we would like to write software which manages a group of animals. There are actions that all of the animals can do, but each animal does it in its own way.

Using interfaces, we can write some code which can work for all of the animals even if each animal behaves differently:

Example

// Interface definition
interface Animal {
  public function makeSound();
}

// Class definitions
class Cat implements Animal {
  public function makeSound() {
    echo " Meow ";
  }
}

class Dog implements Animal {
  public function makeSound() {
    echo " Bark ";
  }
}

class Mouse implements Animal {
  public function makeSound() {
    echo " Squeak ";
  }
}

// Create a list of animals
$cat = new Cat();
$dog = new Dog();
$mouse = new Mouse();
$animals = array($cat, $dog, $mouse);

// Tell the animals to make a sound
foreach($animals as $animal) {
  $animal->makeSound();
}
?>

Try it Yourself »

Example Explained

Cat, Dog and Mouse are all classes that implement the Animal interface, which means that all of them are able to make a sound using the makeSound() method. Because of this, we can loop through all of the animals and tell them to make a sound even if we don't know what type of animal each one is.

Since the interface does not tell the classes how to implement the method, each animal can make a sound in its own way.



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.

Warning

A class can implement two interfaces which define a method with the same name, only if the method declaration in both interfaces is identical.

Warning

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.

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('{' $name '}'$value$template);
        }

         return

$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 A
{
    public function 
foo();
}

interface

extends A
{
    public function 
baz(Baz $baz);
}
// This will work
class implements B
{
    public function 
foo()
    {
    }

    public function

baz(Baz $baz)
    {
    }
}
// This will not work and result in a fatal error
class implements B
{
    public function 
foo()
    {
    }

    public function

baz(Foo $foo)
    {
    }
}
?>

Example #3 Multiple interface inheritance

interface A
{
    public function 
foo();
}

interface

B
{
    public function 
bar();
}

interface

extends AB
{
    public function 
baz();
}

class

implements C
{
    public function 
foo()
    {
    }

    public function

bar()
    {
    }

    public function

baz()
    {
    }
}
?>

Example #4 Interfaces with constants

interface A
{
    const 
'Interface constant';
}
// Prints: Interface constant
echo A::B;

class

implements A
{
    const 
'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 #5 Interfaces with abstract classes

interface A
{
    public function 
foo(string $s): string;

    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 implements A
{
    public function 
foo(string $s): string
    
{
        return 
$s PHP_EOL;
    }
}

class

extends B
{
    public function 
bar(int $i): int
    
{
        return 
$i 2;
    }
}
?>

Example #6 Extending and implementing simultaneously

class One
{
    
/* ... */
}

interface

Usable
{
    
/* ... */
}

interface

Updatable
{
    
/* ... */
}// The keyword order here is important. 'extends' must come first.
class Two extends One implements UsableUpdatable
{
    
/* ... */
}
?>

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.

thanhn2001 at gmail dot com

11 years ago

PHP prevents interface a contant to be overridden by a class/interface that DIRECTLY inherits it.  However, further inheritance allows it.  That means that interface constants are not final as mentioned in a previous comment.  Is this a bug or a feature?

interface a
{
    const
b = 'Interface constant';
}
// Prints: Interface constant
echo a::b;

class

b implements a
{
}
// This works!!!
class c extends b
{
    const
b = 'Class constant';
}

echo

c::b;
?>

vcnbianchi

8 months ago

Just as all interface methods are public, all interface methods are abstract as well.

williebegoode at att dot net

8 years ago

In their book on Design Patterns, Erich Gamma and his associates (AKA: "The Gang of Four") use the term "interface" and "abstract class" interchangeably. In working with PHP and design patterns, the interface, while clearly a "contract" of what to include in an implementation is also a helpful guide for both re-use and making changes. As long as the implemented changes follow the interface (whether it is an interface or abstract class with abstract methods), large complex programs can be safely updated without having to re-code an entire program or module.

In PHP coding with object interfaces (as a keyword) and "interfaces" in the more general context of use that includes both object interfaces and abstract classes, the purpose of "loose binding" (loosely bound objects) for ease of change and re-use is a helpful way to think about both uses of the  term "interface." The focus shifts from "contractual" to "loose binding" for the purpose of cooperative development and re-use.

Why is interface class used?

Why do we use an Interface? It is used to achieve total abstraction. Since java does not support multiple inheritances in the case of class, by using an interface it can achieve multiple inheritances. It is also used to achieve loose coupling.

What is the use of interface and abstract class in PHP?

PHP - Interfaces vs. Interface are similar to abstract classes. The difference between interfaces and abstract classes are: Interfaces cannot have properties, while abstract classes can. All interface methods must be public, while abstract class methods is public or protected.

What is the purpose of an interface?

The purpose of interfaces is to allow the computer to enforce these properties and to know that an object of TYPE T (whatever the interface is ) must have functions called X,Y,Z, etc.

How are interfaces implemented in PHP?

An interface in PHP is made up of methods that don't have any implementations, so they're called abstract methods. All methods in interfaces must be visible to the public. Interfaces vary from classes; a class can only inherit from one class, while an interface can be implemented by a class.