简体   繁体   中英

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?

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;

I suppose you could convert "falsey" values of the null-coalesced string typecast back to null.

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

It's kind of odd looking, but I think it would produce what you want without using isset . In this case, the '' doesn't matter because it will never be used; it could be anything falsey.

For my projects I use one of these lines:

$array = [
    'key_a' => 1000
];

$boolA = (bool)($array['key_a'] ?? false);
$boolB = (bool)($array['key_b'] ?? false);
var_dump($boolA);
var_dump($boolB);

$intA = (int)($array['key_a'] ?? 0);
$intB = (int)($array['key_b'] ?? 0);
var_dump($intA);
var_dump($intB);

$stringA = (string)($array['key_a'] ?? '');
$stringB = (string)($array['key_b'] ?? '');
$stringC = (string)($array['key_a'] ?? '') ?: null;
$stringD = (string)($array['key_b'] ?? '') ?: null;
$stringE = (isset($array['key_b']) ? (string)$array['key_b'] : null);
var_dump($stringA);
var_dump($stringB);
var_dump($stringC);
var_dump($stringD);
var_dump($stringE);

OUTPUT:

bool(true)
bool(false)

int(1000)
int(0)

string(4) "1000"
string(0) ""
string(4) "1000"
NULL
NULL

I'm not entirely sure what you're trying to do but it looks like you're casting in the wrong place.

You can do something like this:

$username = $inputs['username'] ?? null;

// cast $username to string 
if ($username && $username = (string) $username){
   // your code here
}

Old school:

<?php
$bar = null;
if(isset($foo))
    $bar = (string) $foo;

You could drop the null assignment:

isset($foo) && $bar = (string) $foo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM