PHP 接口实现拒绝参数的子类
考虑一下:
class A{}
class B extends A{}
interface I{
// expects object instanceof A
function doSomething(A $a);
}
class C implements I
{
// fails ????
function doSomething(B $b){}
}
在我的构想中,上述内容应该有效,但它不会,因为 php 拒绝要求第一个参数与接口 (I) 中定义的类型 (A) 完全相同的实现。由于 B 是 A 的子类,所以我不明白有什么问题。我在这里错过了什么吗?
consider this:
class A{}
class B extends A{}
interface I{
// expects object instanceof A
function doSomething(A $a);
}
class C implements I
{
// fails ????
function doSomething(B $b){}
}
In my conception the above should work but it doesn't as php rejects that implementation requiring the first parameter to be exactly the same type (A) as defined in the interface (I). Since B is a subclass of A, I don't see whats the problem. Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
class C Implements I
意味着C
和I
之间必须存在子类型关系。这意味着C
类型的对象应该可以在任何需要I
类型的对象的地方使用。在您的情况下,
C
比I
更具限制性,因为它对其doSomething
参数有更精确的要求 -I.doSomething
code> 适用于任何A
,但C.doSomething
需要A
的特定子类型请注意,如果您更改
C.doSomething< /code> 接受任何
A
那么就没有什么可以阻止你向它传递一个B
类型的对象。您不能只需要B
,因为那样您就会破坏子类型约定。理论上,子类型可以对其函数参数更加自由,对其返回类型更加具体(但反之亦然,就像您的情况一样)。在实践中,编程语言可能要求重写方法中的参数类型必须在各处相同。
class C implements I
means that there must be subtype relation betweenC
andI
. It means object of typeC
should be usable wherever an object of typeI
is required.In your case
C
is more restrictive thanI
because it has more precise requirements on itsdoSomething
argument --I.doSomething
is fine with anyA
butC.doSomething
requires a specific subtype ofA
Note that if you change
C.doSomething
to accept anyA
then nothing prevents you to pass it an object of typeB
. You just can't require onlyB
, because then you would break subtyping contract.In theory, subtypes can be more liberal about their function arguments and more specific about their return types (but never vice versa, as it was in your case). In practice, a programming language may require that argument types in overridden methods must be same everywhere.
几乎没有什么办法 -
instanceof
来解决这个问题:little work around-
instanceof
to solve that problem: