This is an old revision of the document!
PHP RFC: Nullable Casting
- Version: 0.9
- Date: 2018-08-07
- Author: David Rodrigues, david.proweb@gmail.com
- Status: Draft
- Discussion at: https://externals.io/message/102997
Introduction
PHP supports expression casting by using (int) expression
, but it doesn't consider that the expression could be a nullable type, as introduced by PHP 7.1. Due to the lack of support for the nullable casting, is necessary to create some additional codes to keep a nullable output as nullable after a casting, for example.
Proposal
The proposal is to add support to nullable casting to current casting feature. Basically, (int)
is the default int casting, and (?int)
will be a nullable int casting. Generally speaking, what changes is the possibility of using a ?
before the type of casting, turning it into a nullable cast.
The difference between casting and nullable casting is that it the expression is null, it should be keeped as null, instead to be forced to the destination cast.
Input | (cast) - default | (?cast) - nullable | Same result? |
---|---|---|---|
int (123) | int (123) | int (123) | Yes |
null | int (0) | null | No |
bool (true) | bool (true) | bool (true) | Yes |
bool (false) | bool (false) | bool (false) | Yes |
null | bool (false) | null | No |
float (1.23) | float (1.23) | float (1.23) | Yes |
null | float (0.0) | null | No |
string (“test”) | string (“test”) | string (“test”) | Yes |
null | string (“”) | null | No |
array ([1, 2, 3]) | array ([1, 2, 3]) | array ([1, 2, 3]) | Yes |
null | array ([]) | null | No |
object ({ a => 1 }) | object ({ a => 1 }) | object ({ a => 1 }) | Yes |
null | object ({}) | null | No |
Note: the (unset)
will not be affected, returning null
in any case.
Example
Backward Incompatible Changes
None.
Proposed PHP Version(s)
PHP 7.NEXT, possibly 7.4.
RFC Impact
To SAPIs
I need help here.
To Existing Extensions
I need help here, but I do not think so.
To Opcache
I need help here.
Proposed Voting Choices
Voting process should requires 2/3+1
when available.
Patches and Tests
I need help here.