Re: [IDEA for RFC] let the "new" operator fail when the __construct() function returns a value.
| From: | Mirco Babin | Date: | Mon, 23 Feb 2026 08:42:51 +0000 |
| Subject: | Re: [IDEA for RFC] let the "new" operator fail when the __construct() function returns a value. | ||
| References: | 1 2 3 4 5 6 7 8 9 10 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-130132@lists.php.net to get a copy of this message | ||
Op za 21 feb 2026 om 17:28 schreef Rowan Tommins [IMSoP] <imsop.php@rwec.co.uk>:
>
> On 20 February 2026 16:07:01 GMT, Mirco Babin <mirco.babin@gmail.com> wrote:
> >Failing early is not always possible. The compiler can not always infere
> >the correct return type.
>
> PHP defines "void" separately from "null", precisely so that the compiler
> doesn't need to infer anything about the returned value. All it has to do
> is distinguish "return;" from "return some_expression;"
>
> Example: https://3v4l.org/cTaBP
>
That is a very good find. Are the following claims correct?
1) The example given would imply that void is not a type.
```php
<?php
function test(): void
{
return NotLoaded::noIdeaWhatThisReturns(); // Compile error
}
echo 'At runtime'."\n";
// Fatal error: A void function must not return a value in ... on line 5
```
2) This example shows that a void function actually returns null.
```php
<?php
function test(): void
{
return;
}
echo 'At runtime'."\n";
var_dump(test());
// At runtime
// NULL
```
3) That would imply that the adjustment in this RFC can never be
implemented. Because the comparison with void can never be made.
It would have to check against null, and that would allow
"return null;" as a valid case, which is unwanted.
```php
$__constructReturnValue = $newed->__construct(...$args);
if ($__constructReturnValue !== void) {
// PHP 8.6: Deprecated: Returning a value from the
// __construct() constructor is deprecated.
// PHP 9: throw new ConstructorError(
// 'The __construct() constructor must not
// return a value.');
}
```
4) That would also imply that the fail early of the implicit ": void"
return type declaration is true for all cases, both typed and untyped.
In all cases it would be a compile error, because the compiler only
checks "return something;" vs. "return;".
It would never throw a TypeError at runtime.
Kind regards,
Mirco Babin