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

Reply via email to