parent
2287695b44
commit
c3b24fdd32
3 changed files with 218 additions and 10 deletions
@ -0,0 +1,47 @@ |
|||||||
|
--TEST-- |
||||||
|
Interface return type covariance with nullable interface and anonymous class |
||||||
|
--FILE-- |
||||||
|
<?php |
||||||
|
|
||||||
|
declare(strict_types=1); |
||||||
|
|
||||||
|
interface TestInterface1 |
||||||
|
{ |
||||||
|
} |
||||||
|
|
||||||
|
interface TestInterface2 extends TestInterface1 |
||||||
|
{ |
||||||
|
} |
||||||
|
|
||||||
|
interface TestInterface3 |
||||||
|
{ |
||||||
|
public function test(): ?TestInterface1; |
||||||
|
} |
||||||
|
|
||||||
|
class TestClass implements TestInterface3 |
||||||
|
{ |
||||||
|
// Covariant: ?TestInterface2 is a subtype of ?TestInterface1 because |
||||||
|
// TestInterface2 extends TestInterface1. |
||||||
|
public function test(): ?TestInterface2 |
||||||
|
{ |
||||||
|
return new class() implements TestInterface2 { |
||||||
|
public function hello(): string { |
||||||
|
return "anon"; |
||||||
|
} |
||||||
|
}; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
function main() |
||||||
|
{ |
||||||
|
$test = new TestClass; |
||||||
|
$result = $test->test(); |
||||||
|
var_dump($result instanceof TestInterface1); |
||||||
|
var_dump($result instanceof TestInterface2); |
||||||
|
var_dump($result === null); |
||||||
|
} |
||||||
|
?> |
||||||
|
--EXPECT-- |
||||||
|
bool(true) |
||||||
|
bool(true) |
||||||
|
bool(false) |
||||||
@ -0,0 +1,51 @@ |
|||||||
|
--TEST-- |
||||||
|
Return type covariance: union narrowing and object subtype |
||||||
|
--FILE-- |
||||||
|
<?php |
||||||
|
|
||||||
|
interface UnionReturnContract |
||||||
|
{ |
||||||
|
public function make(): int|string; |
||||||
|
} |
||||||
|
|
||||||
|
class UnionReturnImpl implements UnionReturnContract |
||||||
|
{ |
||||||
|
// Covariant: narrowing a union return type (int|string -> int) is allowed. |
||||||
|
public function make(): int |
||||||
|
{ |
||||||
|
return 42; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
class BaseType {} |
||||||
|
class ChildType extends BaseType {} |
||||||
|
|
||||||
|
interface ObjectReturnContract |
||||||
|
{ |
||||||
|
public function build(): BaseType; |
||||||
|
} |
||||||
|
|
||||||
|
class ObjectReturnImpl implements ObjectReturnContract |
||||||
|
{ |
||||||
|
// Covariant: returning a subtype (ChildType) for a BaseType return is allowed. |
||||||
|
public function build(): ChildType |
||||||
|
{ |
||||||
|
return new ChildType(); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
function main() |
||||||
|
{ |
||||||
|
$impl = new UnionReturnImpl(); |
||||||
|
var_dump($impl->make()); |
||||||
|
|
||||||
|
$obj = new ObjectReturnImpl(); |
||||||
|
$built = $obj->build(); |
||||||
|
var_dump($built instanceof BaseType); |
||||||
|
var_dump($built instanceof ChildType); |
||||||
|
} |
||||||
|
?> |
||||||
|
--EXPECT-- |
||||||
|
int(42) |
||||||
|
bool(true) |
||||||
|
bool(true) |
||||||
Loading…
Reference in new issue