1

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

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Erik i got it.
1

This is not Java, you can't (unfortunately) overload methods. So, in the end having something like

class d implements b
{
   public function foo()
   {
   }

   public function baz(Foo $foo)
   {
   }

   public function baz(Baz $baz)
   {
   }
}

Will result in

Fatal error: Cannot redeclare d::baz() in [...][...] on line XX

When implementing an interface, you must implement it the same way it is declared. So, since baz is declared with Baz $baz argument, you must implement it with same argument.

class d implements b
{
   public function foo()
   {
   }

   public function baz(Baz $baz)
   {
   }
}

1 Comment

I am grateful. It helped @Nordenheim

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.