PHP的简写为“if(!isset($ var))$ var = 1;”

时间:2014-01-16 22:13:01

标签: php shorthand

是否有简写版本,“如果尚未设置此变量,则将其设置为”?

示例:

switch ($Frequency) {
    case 'Once':
        doSomethingSpecific();
        break;
    case 'Daily':
        $Message = 'Event will occur every day at the same time.';
    case 'Weekly':
        if (!isset($Message)) $Message = 'Event will occur every week on the same day of the week, at the same time.';
    case 'Monthly':
        if (!isset($Message)) $Message = 'Event will occur every month on the same day of the week.';
        doSomething($Message);
        break;
}

1 个答案:

答案 0 :(得分:6)

是的,它被称为三元运算符:

$var = isset($var) ? $var : "Some default";

自PHP 5.3起,还有一个速记版本:

$var = isset($var) ?: "Some default";

PHP 5.3 +的备用版本:

isset($var) ?: $var = "Some default";