Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
}
like image 965
CarlosCarucce Avatar asked Jul 04 '26 03:07

CarlosCarucce


1 Answers

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.

like image 126
Andrej Ludinovskov Avatar answered Jul 06 '26 19:07

Andrej Ludinovskov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!