phpcastingphp-7null-coalescing-operator

How can I type cast when using the null coalescing operator?


Say I have this:

$username = (string) $inputs['username'] ?? null;

If $inputs['username'] is set then I want it to cast to string. If it's not set then $username should be null.

However, at the moment if $inputs['username'] is not set it will be an empty string instead of null.

How can I fix this? Or is this intentional behaviour?


Solution

  • You can only use the null-coalesce operator if the value you want to return in the non-null case is the same as the value you're testing. But in your case you want to cast it when returning.

    So need to use the regular conditional operator and test the value explicitly.

    $username = isset($input['username']) ? (string) $input['username'] : null;