luckyali444 luckyali444 - 2 months ago 15
PHP Question

PHP - Unable to implement the same interface twice

I am trying to Implement an interface twice which extends another interface but unable to figure out why i am getting a Fatal Error

Here's my code:

interface a {
public function foo();
}

interface b extends a {
public function baz(Baz $baz);
}

// This will work
class c implements b {
public function foo() {
}

public function baz(Baz $baz) {
}
}

// This will not work and result in a fatal error
class d implements b {
public function foo() {
}

public function baz(Foo $foo) {
}
}


I am getting this error message:

Fatal error: Declaration of d::baz() must be compatible with b::baz(Baz $baz) in K:\xampp\htdocs\oop\Lec 2\index.php on line 26

Answer

Your class d has implemented the baz method incorrectly. The interface specifies it must take an argument with the typehint Baz but you use the typehint Foo - changing the argument type from the interface is disallowed. The fix, in class d, would be:

<?php

class d implements b
{
   public function foo() {}
   public function baz(Baz $foo) {}
}

The function's args are specified by the interface, and may not change.