Zend PHP 7 Certification – OOP – Interfaces

This post covers the Interfaces section of the OOP chapter when studying for the Zend PHP 7 Certification.

Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.

Interfaces are defined using the interface keyword, in the same way as a standard class, but 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.

<?php
interface iTemplate
{
    public function setVariable($name, $var);
    public function getHtml($template);
}

Multiple implementation is supported, in that classes may implement more than one interface if desired by separating each interface with a comma.

class MyClass implement iTemplate, iTemplate2
{
    public function setVariable($name, $var)
    {
        // Some stuff
    }
    
    public function getHtml($template)
    {
        // Some stuff
    }
}

In addition, interfaces may extend from one or more classes.

interface iTemplate2 extends a, b
{
    public function baz();
}

Classes that implement an interface must have those methods defined. The classes use the implements keyword in the class declaration to implement an interface.

<?php
class MyClass implements iTemplate
{
    public function setVariable($name, $var)
    {
        // Some stuff
    }
    
    public function getHtml($template)
    {
        // Some stuff
    }
}

Otherwise a fatal error will be generated.

 // This will not work
<?php
class BadClass implements iTemplate {
    public function setVariable($name, $var)
    {
        // Some stuff
    }
}

An interface provides a good way to make sure that a particular object contains particular methods.

What is the difference between an interface and an abstract class, and when should you use either of them?

Use an interface when you want to force developers working in your system (yourself included) to implement a set number of methods on the classes they’ll be building.

An interface is always an agreement or a promise. When a class says “I implement interface Y”, it is saying “I promise to have the same public methods that any object with interface Y has”.

Use an abstract class when you want to force developers working in your system (yourself included) to implement a set numbers of methods and you want to provide some base methods that will help them develop their child classes.

An abstract class is the foundation for another object. When a class says “I extend abstract class Y”, it is saying “I use some methods or properties already defined in this other class named Y”.

View the other sections:

Note: This article is based on PHP version 7.0