Page 1 of 1

Method inheritance

Posted: Sat Dec 22, 2007 1:07 pm
by superdezign
I can't seem to create an interface that allows me to specify a class type in the method, then specify a subclass type in the implemented version of the method. I'm trying to find a way to do this without having to manually check the type inside of the implemented method. Here's an example of what I'm after:

Code: Select all

class Item_Abstract
{
    // ...
}

class SpecificItem extends Item_Abstract
{
    // ...
}

interface TestInterface
{
    public function add(Item_Abstract $item);
}

class SpecificAdder implements TestInterface
{
    public function add(SpecificItem $item)
    {
        // ...
    }
}

$adder = new SpecificAdder;
$adder->add(new SpecificItem);
So far, the best I can think of is:

Code: Select all

class SpecificAdder implements TestInterface
{
    public function add(Item_Abstract $item)
    {
        if ($item instanceof SpecificItem) {
            // ...
        }
    }
}

Posted: Sat Dec 22, 2007 1:25 pm
by volka
SpecificAdder has to implement the method of the interface. This method has to accept every Item_Abstract object, not a specific one.
Adding an additional method that takes another type of parameter is a kind of polymorphism/overloading unsupported by php.

Posted: Sat Dec 22, 2007 2:04 pm
by superdezign
So then technically, add() wouldn't even be a part of the interface, but a part of each individual implemented class, and each should be treated separately?

Posted: Sat Dec 22, 2007 2:39 pm
by volka
Well, the interface says "if it's a TestInterface it has a method add(Item_Abstract)"
If you class does not have this method it's not a TestInterface. If you interface makes no sense with this method, the method doesn't belong to the interface.