|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
[2020-04-16 14:15 UTC] pmmaga@php.net
-Status: Open
+Status: Not a bug
[2020-04-16 14:15 UTC] pmmaga@php.net
[2020-04-16 14:16 UTC] derick@php.net
-Status: Not a bug
+Status: Open
[2020-04-16 14:16 UTC] derick@php.net
[2020-04-16 14:17 UTC] peehaa@php.net
-Status: Open
+Status: Not a bug
[2020-04-16 14:17 UTC] peehaa@php.net
[2020-04-16 16:13 UTC] tiffany@php.net
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 03:00:01 2025 UTC |
Description: ------------ We now have contravariance and covariance. With covariance, we can substitute a return type of `object` with a more specific type like `MyCustomClass` for example. We cannot substitute `object` with `MyCustomClass` as a function argument typehint though. I feel this is a bug. Why would it be allowed as a return type but not a typehint? Test script: --------------- <?php class MyClass {} // ---------- interface TestCo { public function testCo(): object; } class TestCoImplementation implements TestCo { public function testCo(): MyClass { return new MyClass; } } $test = new TestCoImplementation; $object = $test->testCo(); var_dump($object); // ---------- interface TestCon { public function testCon(object $object): object; } class TestConImplementation implements TestCon { public function testCon(MyClass $object): object { return $object; } } $test = new TestCoImplementation; $object = $test->testCo(new MyClass); var_dump($object); Expected result: ---------------- I would hope that the Fatal Error is not present and that the second var_dump provides my class instance. Actual result: -------------- /Users/john/Desktop/contract_test.php:25: class MyClass#2 (0) { } PHP Fatal error: Declaration of TestConImplementation::testCon(MyClass $object): object must be compatible with TestCon::testCon(object $object): object in /Users/john/Desktop/contract_test.php on line 37 PHP Stack trace: PHP 1. {main}() /Users/john/Desktop/contract_test.php:0 Fatal error: Declaration of TestConImplementation::testCon(MyClass $object): object must be compatible with TestCon::testCon(object $object): object in /Users/john/Desktop/contract_test.php on line 37 Call Stack: 0.0026 399984 1. {main}() /Users/john/Desktop/contract_test.php:0