Nullable cast (?int)

From: Date: Tue, 31 Jul 2018 18:23:02 +0000
Subject: Nullable cast (?int)
Groups: php.internals 
Request: Send a blank email to internals+get-102997@lists.php.net to get a copy of this message
Currently we have support to (int) cast (and similar). But I do think that we too need a possibility to do a nullable cast. In terms, it will cast to (int) only if value is not null, else it should be keeped as null. $number = 123; (int) $number => 123; (?int) $number => 123; $string = '123'; (int) $string => 123; (?int) $string => 123; $null = null; (int) $null => 0 (?int) $null => null The last example is the biggest problem, because it transforms (int) null to 0, (bool) null to false, (string) null to '', (array) null to []. It could be an incorrect behavior when your parameter requires an ?int, where an int will have a different behavior than null. Example: function increase(?int $number): ?int { if ($number === null) { return null; } return $number + 1; } increase($_POST['number']); // Could causes increase() first argument should be ?int. increase((int) $_POST['number']); // Will works, but will be always int, and if $_POST['number'] is null, then it will fails because will be converted to 0 erroneous. increase((?int) $_POST['number']); // Will works if is an int, string or null, respecting the expected behavior. -- David Rodrigues

« previous php.internals (#102997) next »