PHP 类型提示与接口和抽象类不符? [英] Php type hinting not getting along with interfaces and abstract classes?
问题描述
我认为在代码示例中看到问题比首先编写问题要容易得多.这是我的php代码:
I think it'll be much easier to see the problem in a code example than writing the question in the first place. Here is my php code:
<?php
interface AnInterface
{
public function method();
}
class AClass implements AnInterface
{
public function method()
{
echo __METHOD__;
}
}
abstract class AnAbstractClass
{
abstract public function method( AnInterface $Object );
}
class ConcreteClass extends AnAbstractClass
{
public function method( AClass $Object )
{
$Object->method();
}
}
$Object1 = new ConcreteClass();
$Object2 = new AClass();
$Object1->method( $Object2 );
以上代码导致如下错误:
The above code causes the following error:
致命错误:ConcreteClass::method() 的声明必须与 AnAbstractClass::method() 的声明兼容
Fatal error: Declaration of ConcreteClass::method() must be compatible with that of AnAbstractClass::method()
问题是 php 似乎没有将 AnAbstractClass::method 和 ConcreteClass::method 的签名识别为兼容.难道我做错了什么?谢谢!
The problem is that php doesn't seem to be recognizing the signatures of AnAbstractClass::method and ConcreteClass::method as compatible. Am I doing something wrong? Thanks!
推荐答案
php 似乎无法将
AnAbstractClass::method
和ConcreteClass::method
的签名识别为兼容.
php doesn't seem to be recognizing the signatures of
AnAbstractClass::method
andConcreteClass::method
as compatible.
PHP 是正确的,它们不兼容.通过仅允许将 AClass
(或其子项)的实例传递给 ConcreteClass::method
,您违反了 AnAbstractClass
提供的契约:它的任何子类都必须接受 AnInterface
作为其 method()
的参数.
PHP is correct, they're not compatible. By allowing only instances of AClass
(or its children) to be passed to ConcreteClass::method
, you're breaking the contract that AnAbstractClass
provides: Any of its subclasses must accept AnInterface
as an argument to its method()
.
如果您的示例有效,并且我有另一个类 BClass
实现了 AnInterface
,我们将遇到一种情况,根据 AnAbstractClass
,method()
应该接受 BClass
的实例,而根据 ConcreteClass
,它不应该.
If your example worked, and I had another class BClass
implementing AnInterface
, we'd have a situation where according to AnAbstractClass
, method()
should accept instances of BClass
, while according to ConcreteClass
, it shouldn't.
更改ConcreteClass::method
的签名以匹配AnAbstractClass::method
的签名.
Change your signature for ConcreteClass::method
to match that of AnAbstractClass::method
.
这篇关于PHP 类型提示与接口和抽象类不符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!