我正在尝试为我的服务类创建一个通用接口(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.
换句话说,该方法必须能够根据签名被调用,但不排除:
- 在方法的实现中使用不同的变量名
- 在方法签名中声明的参数之后声明额外的可选参数,如果有的话
从问题中得出,这会起作用:
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/