dtnpzghys01643322 2019-08-13 08:25
浏览 21

接口typehints和继承的奇怪行为[重复]

Here's the situation I have:

interface IFoo {}

class FooImplementation implements IFoo {
    public $someProperty;
}

class SomeParentClass {
    public function someMethod(Ifoo $someParam) {...}
}

class SomeChildClass extends SomeParentClass {
    public function someMethod(FooImplementation $someParam) {
         // do something with someProperty from $someParam
    }
}

When trying to run the someMethod from the SomeChildClass I get a warning saying that

Declaration of SomeChildClass::someMethod should be compatible with SomeParentClass::someMethod

However, I do think they are compatible...

I have a parent class that specifies it needs an object adhering to an interface as parameter, and in it's child class, I'm using a class that implements said interface. Therefor, to me, it is strange that is throws that warning,

While I do understand that when doing a straight up compare in classnames, Ifoo is different than FooImplementation. I feel like what I'm trying to do is correct, unless I'm completely overlooking something here.

EDIT: I understand this is due to PHP not supporting covariance... A follow-up question, in the child class, I need to do something with with a property on the FooImplementation class that is not defined in the interface. How would I best go about doing so?

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?