简体   繁体   中英

Why are not this implementation considered compatible with their interface by PHP?

I have these two interfaces:

interface Observer
{
    public function notify(Observable $observable, ...$args);
}

interface Observable
{
    public static function register(Observer $observer);
    public function notifyObservers();
}

And here is what I am trying to implement:

abstract class EventHandler implements Observer
{
    abstract public function notify(Event $event, ...$args);
}

abstract class Event implements Observable
{
    private static $handlers = [];
    public static function register(EventHandler $handler)
    {
        self::$handlers []= $handler;
    }

    public function notifyObservers()
    {
        //notify loop here...
    }
}

Event is an Observable and EventHandler is an Observer , right?

So why php considers these implementation incompatible with their respective interfaces?


A simple test of what I meant by "compatible":

class CreateEvent extends Event {}

$createEventObj = new CreateEvent();
if ($createEventObj instanceof Observable) {
    echo 'Compatible';
} else {
    echo 'Incompatible';
}

This is because of type hinting. If your typehint is (Observable $observable) you should use exactly the same typehint in all implementation of this method in all sub-classes. Read more here http://php.net/manual/de/language.oop5.typehinting.php .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM