Returning a value from a constructor is deprecated
Description
new X always evaluates to the newly created instance, no matter what __construct() returns: any value returned from a constructor is discarded.
Since explicitly returning a value from __construct() is therefore always misleading dead code, PHP 8.6 deprecates it. A bare return; with no expression, used purely to exit the constructor early, remains unaffected.
Example
<?php
class X {
public function __construct() {
return 42;
}
}
$x = new X;
var_dump($x);
?>
Literal Examples
- Returning a value from a constructor is deprecated
Alternatives
- Use a bare
return;(with no expression) to exit the constructor early. - If you need to build and hand back an object based on some logic, use a static factory method instead of relying on
newand a constructor return value.
Related error messages
- returning-a-value-from-a-destructor-is-deprecated
- making-a-constructor-a-generator-is-deprecated
- constructor-%s::%s()-cannot-declare-a-return-type
- method-%s::__construct()-cannot-declare-a-return-type
Related error messages
Changed Behavior
This error may appear following an evolution in behavior, in previous versions. See constructorReturnDeprecated