php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Doc Bug #75385 PHP does not support covariant return types
Submitted: 2017-10-15 21:41 UTC Modified: 2017-10-16 09:23 UTC
Votes:3
Avg. Score:5.0 ± 0.0
Reproduced:3 of 3 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: carlos at wfmh dot org dot pl Assigned:
Status: Open Package: Scripting Engine problem
PHP Version: 7.2.0RC4 OS: Ubuntu
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2017-10-15 21:41 UTC] carlos at wfmh dot org dot pl
Description:
------------
Having script like that

<?php
class ModelBase {}

class ModelChild extends ModelBase {}

class A {
    public function test(): ModelBase {}
}

class B extends A {
        public function test(): ModelChild {}
}

ordinary

php file.php

throws

PHP Fatal error:  Declaration of B::test(): ModelChild must be compatible with A::test(): ModelBase in file.php on line 13

PHP 7.2.0RC3 (cli) (built: Sep 28 2017 16:28:37) ( NTS )
Copyright (c) 1997-2017 The PHP Group


Test script:
---------------
<?php
class ModelBase {}

class ModelChild extends ModelBase {}

class A {
    public function test(): ModelBase {}
}

class B extends A {
    public function test(): ModelChild {}
}

Expected result:
----------------
As ModelChild extends ModelBase, methods expected to return ModelBase should be allowed to be overriden and return its subclass (ModelChild) as it is allowed in any other language that follows OOP principles.

Actual result:
--------------
PHP Fatal error:  Declaration of B::test(): ModelChild must be compatible with A::test(): ModelBase in file.php on line 13


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-10-15 21:48 UTC] Wes dot example at example dot org
Sadly php doesn't support return type covariance yet.

For now you can doc-comment /** @return ModelChild */ in class B.
 [2017-10-15 21:55 UTC] stas@php.net
-Package: PHP Language Specification +Package: *General Issues
 [2017-10-16 09:22 UTC] cmb@php.net
-Summary: Fatal error after overriding method and returning subclass of what parent do +Summary: PH does not allow covariant return types -Type: Bug +Type: Documentation Problem -Package: *General Issues +Package: Scripting Engine problem
 [2017-10-16 09:22 UTC] cmb@php.net
It seems that is not properly documented.
 [2017-10-16 09:23 UTC] cmb@php.net
-Summary: PH does not allow covariant return types +Summary: PHP does not support covariant return types
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Tue Sep 17 08:01:27 2019 UTC