Php类型暗示不与接口和抽象类相处? [英] Php type hinting not getting along with interfaces and abstract classes?

查看:148
本文介绍了Php类型暗示不与接口和抽象类相处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为在代码示例中查看问题要比首先编写问题容易得多。这是我的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是正确的,它们兼容。通过只允许 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

这篇关于Php类型暗示不与接口和抽象类相处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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