php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #73435 Return type-hinting polymorphism
Submitted: 2016-11-01 17:31 UTC Modified: 2016-11-01 17:39 UTC
From: php at haravikk dot me Assigned:
Status: Duplicate Package: Scripting Engine problem
PHP Version: 7.0.12 OS:
Private report: No CVE-ID: None
 [2016-11-01 17:31 UTC] php at haravikk dot me
Description:
------------
I'd like to propose that when implementing/extending that type-hints for return values can be fulfilled by any sub-class of the same type.

In other words, sub-classes, when implementing/extending a method, should be able to provide a stricter type-hint for their return value, so long as it is a sub-class of the parent's type-hint.

Please see the test script for an example; in it I would expect to be able to provide a return type-hint of "Bar", as it is a sub-type of "Foo", therefore meeting the original requirements while clarifying that the sub-class is more specific in what specific flavour of "Foo" it will actually return.

There is a similar issue (#60107) in which the Liskov Substitution Principle is referenced, however, while allowing this behaviour on method arguments might breach LSP, I believe doing so only for return types should be okay.

Test script:
---------------
class Foo {}
class Bar extends Foo {}

abstract class MyType {
    abstract function example(): Foo;
}

class MyTypeImpl extends MyType {
    function example(): Bar { /* Do something here */ }
}


Expected result:
----------------
The implementation of the example method by "MyTypeImpl" should be accepted as a valid implementation of the method in "MyType".

Actual result:
--------------
Fatal error: Declaration of MyTypeImpl::example(Bar $value) must be compatible with MyType::example(Foo $value) in test.php on line 12

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-11-01 17:39 UTC] requinix@php.net
-Status: Open +Status: Duplicate -Package: PHP Language Specification +Package: Scripting Engine problem
 [2016-11-01 17:39 UTC] requinix@php.net
Duplicate of request #72442.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Nov 22 23:01:29 2024 UTC