PHP VERSION: 8.2.18

function_return_types_valid.php

<?php

// Overriding a method that did not have a return type:
class Test
{
    public function 
getDateTime(string $time NULL)
    {
        if (
$time) {
            return new 
DateTime($time);
        }
        return 
NULL;
    }
}
class 
Special extends Test
{
    public function 
getDateTime(string $time NULL): DateTime
    
{
        return 
parent::getDateTime($time);
    }
}

$test    = new Test();
$special = new Special();

// returns DateTime
var_dump($test->getDateTime('2015-09-01'));
// returns NULL
var_dump($test->getDateTime());
// returns DateTime
var_dump($special->getDateTime('2015-09-01'));
// generates error
try {
    
var_dump($special->getDateTime());
} catch (
Error $e) {
    echo 
'ERROR: ' $e->getMessage();
}



Output


object(DateTime)#3 (3) {
  ["date"]=>
  string(26) "2015-09-01 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}
NULL
object(DateTime)#3 (3) {
  ["date"]=>
  string(26) "2015-09-01 00:00:00.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(16) "America/New_York"
}
ERROR: Special::getDateTime(): Return value must be of type DateTime, null returned
SOURCE CODE