A class’ constructor and destructor (“Lifecycle Functions”) are special in that they are not meant to be used like regular methods and called manually. Observing the return value during intended use is not possible.
To that effect they are already restricted from declaring any return type at all, including declaring a return type of void. It however is nevertheless legal to return a value from these methods, which can be confusing, particularly when returning a separate valid object instance from __construct().
Deprecate returning values from __construct() and __destruct(). Using return …; shall emit a compile-time deprecation. Using return; without an expression to “skip” over the remaining logic shall remain legal. Starting with the next major version, returning a value shall emit a compile-time error.
<?php class Foo { public function __construct() { return 123; // Deprecated: Returning a value from a constructor is deprecated in test.php on line 6 } public function __destruct() { return 123; // Deprecated: Returning a value from a constructor is deprecated in test.php on line 11 } } class Bar { public function __construct() { if (random_int(0, 1)) { return; // Skipping the rest of the logic remains legal. } echo "Constructing", PHP_EOL; } }
This deprecation is in line with the existing error when returning a value from a void function:
<?php function void_function(): void { return 123; // Fatal error: A void function must not return a value in test.php on line 5 }
It will remain legal to manually call __construct() and __destruct(), for example to call a parent constructor or destructor - or to initialize a lazy object.
The deprecation itself is not a backwards incompatible change. When it is turned into an error, code that returns values will stop working. The justification is provided in the introduction.
Deprecation in the next PHP version (8.6). Removal in the first major after that.
Static analyzers and IDEs will want to point out:
None.
None.
None.
Similar arguments apply to __clone(). However in that case specifying an explicit return type of void is legal. __clone() will therefore implicitly be handled if / when magic methods are required to specify accurate return (and parameter) types.
Primary Vote requiring a 2/3 majority to accept the RFC:
After the RFC is implemented, this section should contain:
new emit an error if a value is returned: https://news-web.php.net/php.internals/129980None.