PHP接口(interface)可选参数

标签 php oop interface

我正在尝试为我的服务类创建一个通用接口(interface)。我在使用接口(interface)的两个类上遇到了麻烦。他们共享一个名为 create 的方法。 create 方法除了三个参数。我希望第三个参数是可选的,这样两个类都可以使用它。

interface ServiceInterface{

    public static function create($var1, $var2, $thisOneIsOptional);

}

class ServiceObject1 implements ServiceInterface{

    public static function create($url, $server){
       //....
    }
 }

class ServiceObject2 implements ServiceInterface{

    public static function create($methode, $url, $id){
       //....
    }
}

最佳答案

实现定义为父类抽象签名或由接口(interface)定义的方法的类必须遵循特定规则,但它们不必完全匹配。

这没有很好的记录,例如 PHP documentation of interfaces 中甚至没有提到它, 但被 documentation of abstract classes 触及:

Furthermore the signatures of the methods must match, i.e. the type hints and the number of required arguments must be the same. For example, if the child class defines an optional argument, where the abstract method's signature does not, there is no conflict in the signature.

换句话说,该方法必须能够根据签名被调用,但不排除:

  1. 在方法的实现中使用不同的变量名
  2. 在方法签名中声明的参数之后声明额外的可选参数,如果有的话

从问题中得出,这会起作用:

interface ServiceInterface{

    public static function create($var1, $var2);

}

class ServiceObject1 implements ServiceInterface{

    public static function create($url, $server){
       //....
    }
 }

class ServiceObject2 implements ServiceInterface{

    public static function create($methode, $url, $id = null){
       //....
    }
}

关于PHP接口(interface)可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44046415/

相关文章:

javascript - 允许在文本区域中输入 HTML

php - 红色的颜色边框输入( Twig )

c++ 重载 < 在 C++ 中对多个类使用友元函数?

Typescript接口(interface)调用方法

android - Kotlin : Casting an object to Generic class

c# - 从模板类转换

php - 如何设置 php 以便将数据插入数据库?

php - 我的 MySql 语法问题(我认为)

java - 将 FutureTasks 提交给 Executor - 为什么它有效?

javascript - 使用 React hooks 将基于类的组件转换为功能组件