marcosh
marcosh

Reputation: 9008

Expanded implementation of php interfaces

PHP's manual on Object Interfaces says:

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

No consider the following case: I have an interface

interface Foo
{
    public function foo(SpecialClass $object);
}

which contains just a method foo which takes a SpecialClass as an argument, and a concrete class

class Bar
{
    public function foo(BaseClass $object)
    {
        // do something with $object
    }
}

that has the same signature of Foo excepts of the fact that foo takes a BaseClass, where SpecialClass implements BaseClass.

Thinking theoretically, whenever in my code I need something to satify Foo interface, I could use an instance of Bar and everything should work (beacuse a SpecialClass is a BaseClass). In other words, Bar satisfies the contract declared by Foo because it has a method foo that is able to handle any SpecialClass object.

To make this explicit, and be able to actually use it in my code, I'd like to be able to write Bar implements Foo, but that, as stated in the documentation, throws a fatal error.

What is the reason for this fatal error? Is it just because things are done like this at the moment or is there a specific reason to do things this way?

Upvotes: 0

Views: 60

Answers (2)

Pavel Petrov
Pavel Petrov

Reputation: 867

As stated by @dynamic DataTime is not stdClass. Take a look at the following example.

class A {
    public function foo();
}

class B extends A {
    public function foo();
    public function bar();
}

interface C {
   public function baz(B $obj)
}

class D implements C {
    public function baz(A $obj);
}

You can see that the C interface's function baz takes argument B. The implementation however takes argument A. The problem is that B has more extended interface and A doesn't satisfy it. In other words C interface is requiring access the foo() and bar(). But A has only foo(). If it was the opposite however the things would work - B satisfies the A's interface.

So this is not a temporary behavior and is correct one.

Upvotes: 0

dynamic
dynamic

Reputation: 48141

DateTime is not a StdClass, they are actually two different class.

This is not Java, where everyone extends from Object

Upvotes: 1

Related Questions