Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP Object-Oriented PHP Basics (Retired) Inheritance, Interfaces, and Exceptions Object Interfaces

Interfaces

Loving the PHP OOP series but slightly unclear about the interfaces. Would be useful if the concept could be rather explained applying a real world example. e.g. the Product class we been working on.

1 Answer

Scott Evans
Scott Evans
4,236 Points

Hi Muhammad.

In my own words, an interface is a declaration of a class and its methods. These methods would be "empty", therefore having no functionality. Below is an exmaple of an interface's method.

public function setVariable($name, $var);

As you can see this is purely just a declaration, there is no functionality within this function....yet! Let now build a simple PHP interface.

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

The idea behind PHP interfaceS is to act as a sort of Class template. You build an interface, you specify methods within this interface, then any class that wants to use this interface is required to implement the methods functionality. Below is a further example of how a class would use our above interface.

class Template implements iTemplate{
    private $vars = array();

    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;
    }
}

As you can see each of the method defined in the interface have been implemented int he template class. PHP would throw fatal error if you were not to implement all of an interfaces methods.

Hope this helps, Scott.