我正在开发一个 PHP (7.4) 库,并且需要将特征用于新功能,但我遇到了参数类型协方差的问题。
我有一个像这样的抽象父类:
<?php
abstract class ParentClass {
abstract public function parentMethod($param): bool;
}
?>
我还有一个特点:
<?php
trait MyTrait {
abstract public function traitMethod($param): bool;
}
?>
我在子类中同时使用类和特征:
<?php
class ChildClass extends ParentClass {
use MyTrait;
// implementation of the abstract methods
public function parentMethod(int $param): bool { // change parent method parameter type
// implementation
}
public function traitMethod(int $param): bool { // change trait method parameter type
// implementation
}
}
?>
这里的问题是我收到此错误:
致命错误:声明 ChildClass::parentMethod(int $param): bool 必须与 ParentClass::parentMethod($param): bool 兼容
似乎我无法更改 parentMethod() 参数类型。如果我删除int
parentMethod() 定义上的类型,我不会收到错误消息!即使在 trait 方法上有一个特定的类型参数。
为什么我可以将协变参数类型与特征抽象方法一起使用,但不能与抽象类方法一起使用?