【发布时间】:2019-11-12 09:30:55
【问题描述】:
可以在界面中输入提示self:
interface I {
public function instanceOfSelf(self $object);
}
class A implements I {
private function printBool(bool $b) {
echo ($b ? 'true' : 'false') . "\n";
}
public function instanceOfSelf(I $object) {
$this->printBool($object instanceof I);
}
}
$a = new A;
$a->instanceOfSelf($a); // true
也可以在界面中输入提示parent,这意味着下面的代码不会产生错误:
interface I1 {}
interface I2 extends I1 {
public function instanceOfSelf(self $object);
public function instanceOfParent(parent $object);
}
但是,当根据I2::instanceOfParent 提示I1 时会抛出错误:
// Duplication for completion...
interface I1 {}
interface I2 extends I1 {
public function instanceOfSelf(self $object);
public function instanceOfParent(parent $object);
}
class A implements I1 {}
class B implements I2 {
private function printBool(bool $b) {
echo ($b ? 'true' : 'false') . "\n";
}
public function instanceOfSelf(I2 $object) {
$this->printBool($object instanceof I2);
}
public function instanceOfParent(I1 $object) {
$this->printBool($object instanceof I1);
}
}
$a = new A;
$b = new B;
$b->instanceOfSelf($b); // true
$b->instanceOfParent($a); // true
$b->instanceOfParent($b); // true
这会产生以下错误(PHP 5.6.30、7.3.3、7.4.0):
Fatal error: Declaration of B::instanceOfParent(I1 $object) must be compatible with I2::instanceOfParent(parent $object)
那么如果
I1不是I2的父级,那么谁是?这是一个已知的错误,可以在界面中键入提示
parent而无法实现此功能?
【问题讨论】:
标签: php inheritance interface php-7 type-hinting