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
View Add Comment Developer Edit
Anyone can comment on a bug. Have a simpler test case? Does it work for you on a different platform? Let us know!
Just going to say 'Me too!'? Don't clutter the database with that please !
Your email address:
MUST BE VALID
Solve the problem:
14 + 1 = ?
Subscribe to this entry?

 
 [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

Add a Patch

Pull Requests

Add a Pull Request

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: Thu Mar 28 10:01:26 2024 UTC