Method inheritance

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Method inheritance

Post 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) {
            // ...
        }
    }
}
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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.
Post Reply