According to PHP documentation for return type declarations (emphasis mine):
.... In the default weak mode, returned values will be coerced to the correct type if they are not already of that type.
This means that the method returnInt()
class A {
public function returnInt(): int {
return "6a";
}
}
will return the int value 6 (as it should).
However returning null
from the function above throws a TypeError, even though null can be easily coerced to the integer 0 with (int) null
FATAL ERROR Uncaught TypeError: Return value of A::returnInt() must be of the type integer, null returned
How come this won't work for null values?
What logic is PHP using when attempting type coercion?
This is expected and by design. You can find the original RFC for this feature at http://wiki.php.net/rfc/return_types.
Specifically there is a section Disallowing NULL on Return Types
which states:
this type of situation is common in many languages including PHP. By design this RFC does not allow null to be returned in this situation for two reasons:
- This aligns with current parameter type behavior. When parameters have a type declared, a value of null is not allowed.
- Allowing null by default works against the purpose of type declarations. Type declarations make it easier to reason about the surrounding code. If null was allowed the programmer would always have to worry about the null case.
Now, I can't see in this rfc any talk of type conversion, whereas the official docs do, so chances are null isn't converted simply because the RFC was explicit in saying it wasn't to work. Personally I think leaving null as the odd one out is weird. It was potentially also being consider as linked with the nullable types rfc, which may have made a difference to how null was determined to work.
I can't say I personally agree with how it's worked out, but I'm not a core developer :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With