Вопрос

Is there a shorthand version for, "if this variable isn't set yet, then set it"?

Example:

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;
}
Это было полезно?

Решение

Yes it's called the ternary operator:

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

Since PHP 5.3 there's a shorthand version for this as well:

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

And an alternate version for PHP 5.3+:

isset($var) ?: $var = "Some default";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top