PHP 8.1 – Return types for internal methods

PHP 8.1 – Return types for internal methods

house internal

Every PHP internal methods from internal Classes will now contain a return type declarations. This change will impact any case of extending and overriding of internal PHP classes with custom implementations. From 8.1 we will get a deprecation and since 9.0 it will be a Fatal Error.

Non-final internal method return types – when possible – are declared tentatively in PHP 8.1, and they will become enforced in PHP 9.0. It means that in PHP 8.x versions, a “deprecated” notice is raised during inheritance checks when an internal method is overridden in a way that the return types are incompatible, and PHP 9.0 will make these a fatal error. A few examples:

The overriding method doesn’t declare any return type (PHP 8.1):

class MyDateTime extends DateTime
{
    public function modify(string $modifier) { return false; }
}
 
// Deprecated: Declaration of MyDateTime::modify(string $modifier) should be
// compatible with DateTime::modify(string $modifier): DateTime|false

The overriding method doesn’t declare any return type (PHP 9.0):

class MyDateTime extends DateTime
{
    public function modify(string $modifier) { return false; }
}
 
// Fatal error: Declaration of MyDateTime::modify(string $modifier) must be
// compatible with DateTime::modify(string $modifier): DateTime|false

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.