barbushin
barbushin

Reputation: 5305

Multiple interfaces requirements for function argument

Is there any way to realize something like this in PHP?

interface Editable {}
interface Deletable {}

function clear(Editable Deletable $object) {
...
}

Upvotes: 2

Views: 232

Answers (2)

Angry Dan
Angry Dan

Reputation: 3281

If I were you and I had this as a problem I would probably do something like this:

interface Editable {}
interface Deletable {}

function clear($object) {
    if( $object instanceof Editable ){
        ...
    }elseif( $object instanceof Deletable  ){
        ...
    }else{
        throw new InvalidArgumentException("\$object must be of type 'Editable' or 'Deletable' but " . get_class($object) . " was provided.");
    }
    ...
}

Rather than trying to build up an interface just for the signature of one argument I would be more inclined to handle the argument in the function body itself and remove the strict requirement from the signature. The Exception is just there to keep things tidy if you do get a bad argument.

Upvotes: 1

Dennis
Dennis

Reputation: 2142

You can extend interfaces like classes:

interface Editable {}
interface Deletable {}
interface EditAndDeletable extends Editable, Deletable {}

function clear(EditAndDeletable  $object) {
...
}

The type of $object now has to implement all methods of Editable and Deleteable.

Upvotes: 4

Related Questions