PHP OOP“实现必须兼容" [英] PHP OOP "Implementation must be compatible"

查看:54
本文介绍了PHP OOP“实现必须兼容"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 PHP OOP 和类型提示方面遇到了奇怪的问题.举个例子:

I'm having weird problems with PHP OOP and type hinting. 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) {}
}

这段代码不会运行,说明method与接口声明不兼容.我认为它是兼容的,因为 C 扩展了 AC - 我错过了什么吗?我应该如何实现这种功能?

This code won't run, saying that method is not compatible with the interface declaration. I would think it is compatible since C extends AC - do I miss something? How am I expected to implement this sort of functionality?

推荐答案

假设你有一个 B 类,它也扩展了 AC.然后 I 要求它的任何实现也接受 B 作为方法的参数.但是,您的 InterfaceImplementation 没有.

Imagine you have a class B which also extends AC. Then I requires that any of its implementations also accept B as argument to method. Your InterfaceImplementation, however, doesn't.

大局:如果您需要在实现中指定具体类型,您可能需要重新考虑您的设计.这个想法是,对于外部世界,所有需要知道的都是由 AC 编码的,不应该有一个 InterfaceImplementation 需要知道哪个具体的子类转移.也许特定的东西可以嵌入到 C 的代码中,并通过 AC 公开的方法进行通用调用?

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. Maybe the specific stuff can be embedded in C's code and generically called through a method exposed by AC?

另一个更新:您可以使用泛型实现您想要的功能,但我认为它们不存在于 PHP 中.我仍然认为如果你分享设计问题的细节,可能会提出另一个有趣的问题:)

Yet another update: You might be able to achieve what you want using generics, but I don't think they exist in PHP. I still think if you share the details of the design problem that might make another interesting question :)

这篇关于PHP OOP“实现必须兼容"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆