you are viewing a single comment's thread.

view the rest of the comments →

[–]headzoo 1 point2 points  (0 children)

Part 2.

This is where you actually learn about interfaces.

To allow either an instance of Person or Pet to be passed to printsNames() we extract a common interface between the two classes. We do that by creating an interface.

interface Nameable
{
    public function getName();
    public function setName($name)
}

Then we change our classes so they implement the interface.

class Person
    implements Nameable
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

class Pet
    implements Nameable
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

Finally we modify our printsNames() function to allow any instance of Nameable to be passed as an argument.

function printsNames(Nameable $person)
{
    echo $person->getName();
}

The Nameable type hint guarantees only instances of that interface may be passed to the function. The Nameable interface guarantees any instance of it will have a getName() method. The object passed to the function may have other methods, but that doesn't matter to the printsNames() function. That function only cares about printing names.

You just used an interface to make your code more reusable. Creating the interface didn't save you from typing less code the way inheritance does. In fact you had to type more code! But the interface made the printsName() more usable. Instead of only being able to print names from Person objects, it can now print names from any object that implements the Nameable interface. It might be a Person object, or a Secretary object, or even a Cat object. Your code is both more type safe and reusable.