Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Returntype Covariance

PHP added the support of return type covariance. Since PHP 7.4, the return type of a child class may be more strict than the one of the parent.

In PHP 7.3, the child method must have the same return type than the parent.

PHP code

<?php

interface I {}

interface J extends I {}

class X {
	function foo() : I {
	
	}
}

class Y extends X {
	function foo() : J {
	
	}
}

var_dump(new Y);

?>

Before

PHP Fatal error:  Declaration of y::foo(): j must be compatible with x::foo(): i 

Fatal error: Declaration of y::foo(): j must be compatible with x::foo(): i 

After

object(y)#1 (0) {
}

PHP version change

This behavior changed in 7.4.

Error Messages

Extension

© 2023-2026, Damien Seguy - Exakat