Skip to content

Instantly share code, notes, and snippets.

@bagart
Last active May 25, 2022 12:51
Show Gist options
  • Save bagart/ceb8225f152cd13463268090f8ded18f to your computer and use it in GitHub Desktop.
Save bagart/ceb8225f152cd13463268090f8ded18f to your computer and use it in GitHub Desktop.
>< of parent/children class
<?php
declare(strict_types=1);
class A
{
}
class B extends A
{
}
class C extends B
{
}
class TestA
{
public function x(C $c):A
{
return new C();
}
}
class TestB extends TestA
{
public function x(B $b):B
{
return new C();
}
}
class TestC extends TestB
{
public function x(A $a): C
{
return new C();
}
}
$c = new C();
$testA = new TestA();
$testC = new TestC();
$resultA = $testA->x($c);
$resultC = $testC->x($c);
var_dump([
'TestA::x(C): expect C' => get_class($resultA),
'TestC::x(C): expect C' => get_class($resultC),
]);
$a = new A();
try {
$resultA = $testA->x($a);
echo "impossible";
} catch (TypeError $e){
echo "TestA::x(A): expected TypeError\n";
}
echo 'TestC::x(A): expect C => '. get_class($testC->x($a));
@bagart
Copy link
Author

bagart commented May 25, 2022

https://3v4l.org/WV4jo

Output for 7.4.0 - 7.4.29, 8.0.1 - 8.0.19, 8.1.0 - 8.1.6
array(2) {
  ["TestA::x(C): expect C"]=>
  string(1) "C"
  ["TestC::x(C): expect C"]=>
  string(1) "C"
}
TestA::x(A): expected TypeError
TestC::x(A): expect C => C

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment