It is possible to type hint self inside an interface:
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
It is also possible to type hint parent inside an interface, which means the following code produces no error:
interface I1 {}
interface I2 extends I1 {
public function instanceOfSelf(self $object);
public function instanceOfParent(parent $object);
}
However when type hinting I1 according to I2::instanceOfParent an error is thrown:
// 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
This produces the following error (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)
So if
I1is not the parent ofI2, who is?Is this a known bug, that it is possible to type hint
parentin an interface without the ability to implement this feature?