【问题标题】:php implement same functions from differents interfacesphp从不同的接口实现相同的功能
【发布时间】:2021-02-04 05:10:49
【问题描述】:

有很多 php 组件,每个组件都需要实现自己的接口或类似 psr 的东西。

如果我必须从不同的组件实现两个不同的接口,并且这些接口具有相同的功能,换句话说,相同的签名或功能名称,

我可以在一个类中实现这些接口吗?

喜欢这种情况。

interface I1FromComponent1 {
    function getName:string
}

interface I2FromComponent2 {
    function getName:Name(or NameInterface)
}

Myclass {

function getName():string {
    return $this->name;
}

}

【问题讨论】:

  • 这是众所周知的问题,可以使用旨在解决此特定问题的策略设计模式来解决。您可以从网络上找到许多关于如何实现这一点的资源。
  • @Dashrath Chauhan 感谢您的建议,但我不想仅仅因为这个问题而改变我的风格。
  • @Julian S 是的,但它太旧了。问题是即使在将来,相同的函数名也不能保证相同的功能,php 支持重载 this 永远无法解决。有 psr 但对其他开发者来说太严格了。
  • 接口的目的是让您通过接口进行设计,并且对函数的调用知道返回的是什么类型,并且可以适当地采取行动。如果它可以返回stringName,如果您的代码将函数调用视为期待Name 返回类型,那么string 类型会发生什么?

标签: php


【解决方案1】:

PHP 不支持方法重载,为了解决这个问题,PHP Manual 声明了它是 OOP 的实现...

一个类可以实现两个定义同名方法的接口,前提是两个接口中的方法声明相同

接口的目的是确保在整个代码中一致地使用函数,并与支持这些功能的 IDE 中的类型提示和代码嗅探相关联。如果没有重载,代码如何处理这样的事情?

// Works for string return type, but will only return a string for
// NameInteface return type if it implements the __toString() method
echo $this->getName();

// Works for NameInterface return type, but fails for string return type
$var2 = $this->getName()->nameMethod;

您最好的选择是让接口定义不同的方法,每个返回类型一个:

interface I1FromComponent1 {
    function getName() : string;
}
    
interface I2FromComponent2 {
    function getNameObject() : NameInterface;
}

【讨论】:

  • 绝对是最好的选择,如果我可以编辑使用这些接口的整个代码!谢谢?
猜你喜欢
  • 2020-07-25
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多