php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #73985 Return type of the child may not match the parent
Submitted: 2017-01-24 12:54 UTC Modified: 2017-01-24 14:29 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:0 (0.0%)
Same OS:0 (0.0%)
From: david at grudl dot com Assigned:
Status: Duplicate Package: Class/Object related
PHP Version: 7.1.1 OS:
Private report: No CVE-ID: None
 [2017-01-24 12:54 UTC] david at grudl dot com
Description:
------------
Return type of the child must match the parent:

This code leads to "Fatal error: Declaration of B::test(): string must be compatible with A::test(): int"

<?php

class A
{
	function test(): int 
	{}
}

class B extends A
{
	function test(): string
	{}
}
?>

But it's okay, if I add interface:

<?php

interface I
{
	function test();
}

class A implements I
{
	function test(): int 
	{}
}

class B extends A
{
	function test(): string
	{}
}
?>

Expected result:
----------------
Fatal error: Declaration of B::test(): string must be compatible with A::test(): int

Actual result:
--------------
no error

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2017-01-24 14:29 UTC] requinix@php.net
-Status: Open +Status: Duplicate
 [2017-01-24 14:29 UTC] requinix@php.net
This happens because the method is being validated against the original definition, not the parent. Since test() was defined in I, A::test is validated against I::test (succesfully) and B::test is validated against I::test (successfully) so the A<->B problem won't be reported.

You can see this behavior by making I::example() return int: https://3v4l.org/V71FR
> Fatal error: Declaration of B::test(): string must be compatible with I::test(): int

I just wrote up a longer bug report about this behavior (which also happens with method parameters) as bug #73987 so I'm marking this one as a duplicate.
 
PHP Copyright © 2001-2017 The PHP Group
All rights reserved.
Last updated: Sun Nov 19 01:31:42 2017 UTC