Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have an exposed implementation for abstract interfaces?

Tags:

oop

php

abstract

The concept I'm thinking of comes from the Traversable interface. This interface cannot be directly implemented, but instead is satisfied by implementing an interface that extends it.

Can I declare an interface that cannot be implemented and instead extend with public interfaces?

Edit: I realize the possibility would be rather pointless as it could be circumvented by a third party creating an interface that could extend the base interface. I'm looking for a cleaner way to express polymorphism.

For example:

abstract interface Vehicle
{
}

interface Car extends Vehicle
{
    public function drive(RouteProvider $routeProvider, $speed)
}

interface Boat extends Vehicle
{
    public function sail(BodyOfWater $water, $heading);
}

class PeopleMover
{
    public function move(Vehicle $vehicle)
    {
        if ($vehicle instanceof Boat) {
            // move people across bodies of water
        } elseif ($vehicle instanceof Car) {
            // move people along roads
        }
    }
}
like image 727
Steve Buzonas Avatar asked Jan 19 '15 18:01

Steve Buzonas


1 Answers

The purpose of an interface is to define how an application access your object, rather control how objects are defined. It's a way for your object to state to the application, "I implement this interface, so you can trust I have these methods."

If you want to control how objects are defined, you should use abstract classes with abstract methods.

like image 94
Courtney Miles Avatar answered Oct 05 '22 02:10

Courtney Miles