简体   繁体   中英

Ternary operator when casting a variable

While writing is_numeric($var) ? (Int)$var : (String)$var; is_numeric($var) ? (Int)$var : (String)$var; , I was wondering if it could be possible to move the ternary operator to the part where I cast the variable:

echo (is_numeric($var) ? Int : String)$var;

Not to my surprise, it didn't work:

PHP Parse error: syntax error, unexpected '$var' (T_VARIABLE)

Is this at all possible? Or maybe something close to what I'm trying to do? It's more of a curiosity thing than a need to use it.

Yes it's possible. This should work for you:

var_dump((is_numeric($var)?(int)$var :(string)$var));

As an example to test it you can easy do this:

$var = 5;
var_dump((true?(int)$var :(string)$var)); //Or var_dump((false?(int)$var :(string)$var));

Output:

int(5)  //string(1) "5"

EDIT:

They only way i could think of to do something similar to what you want would be this:

settype($var, (is_numeric($var)?"int":"string")); 
var_dump($var);

No; this is not possible. The ternary operator expects an expression which the casting operator is not.

It would however be possible to use first-class functions, which are expressions, with the ternary operator like so:

$toInt = function($var) {
    return (int) $var;
};

$toString = function($var) {
    return (string) $var;
};

$foo = "10";

var_dump(call_user_func(is_numeric($foo) ? $toInt : $toString, $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