简体   繁体   English

PHP OOP“实现必须兼容”

[英]PHP OOP “Implementation must be compatible”

I'm having weird problems with PHP OOP and type hinting. 我在使用PHP OOP和类型提示时遇到了奇怪的问题。 Here's an example: 这是一个例子:

abstract class AC {}

class C extends AC {}

interface I {
    function method(AC $abstract);
}

class InterfaceImplementation implements I {
    function method(C $concrete) {}
}

This code won't run, saying that method is not compatible with the interface declaration. 该代码不会运行,表示该method与接口声明不兼容。 I would think it is compatible since C extends AC - do I miss something? 我认为这是兼容的,因为C扩展了AC-我会错过吗? How am I expected to implement this sort of functionality? 我应该如何实现这种功能?

Imagine you have a class B which also extends AC . 假设您有一个B类,它也扩展了AC Then I requires that any of its implementations also accept B as argument to method. 然后, I要求它的任何实现也都接受B作为方法的参数。 Your InterfaceImplementation , however, doesn't. 但是,您的InterfaceImplementation却没有。

The bigger picture: You might want to reconsider your design if you need to specify a concrete type in the implementation. 更大的图景:如果需要在实现中指定具体类型,则可能需要重新考虑设计。 The idea is that to the outside world, all that needs to be known is encoded by AC and there should not be an InterfaceImplementation that ever needs to know which concrete subclass is being transferred. 这个想法是,对于外界,所有需要知道的都是由AC编码的,并且不应有一个InterfaceImplementation曾经需要知道要传输哪个具体子类。 Maybe the specific stuff can be embedded in C 's code and generically called through a method exposed by AC? 也许特定的东西可以嵌入到C的代码中,并通过AC?公开的方法进行通用调用AC?

Yet another update: You might be able to achieve what you want using generics, but I don't think they exist in PHP. 另一个更新:使用泛型可以实现所需的功能,但我认为它们不存在于PHP中。 I still think if you share the details of the design problem that might make another interesting question :) 我仍然认为,如果您分享设计问题的细节,可能会引起另一个有趣的问题:)

Just define it as : 只需将其定义为:

class InterfaceImplementation implements I {
    function method(AC $concrete) {}
}

And call it with an instance of C, ie. 并使用C的实例调用它,即。 ->method(new C()); .

The PHP reference manual on Object Interfaces clearly states : 有关对象接口的PHP参考手册明确指出:

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. 不这样做将导致致命错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM