Any more concise way to set default values?

柔情痞子 提交于 2019-11-29 11:00:00

Here is a shorter syntax:

isset($v) || $v="default value";

TL;DR - No, that expression can't be made any shorter.

What you want is for the shortened ternary expression to perform an implicit isset(). This has been discussed on the mailing list and an ifsetor RFC has been created that covers the concept as well.

Since the shortened ternary operator already existed at the time of the above discussion, something like this was proposed using a non-existent operator ??:

// PROPOSAL ONLY, DOES NOT WORK
$v = $v ?? 'default value';

Assign 'default value' if $v is undefined.

However, nothing like this has been implemented in the main language to date. Until then, what you have written can't be made any shorter.

This horrible construct is shorter, but note that it's not the same because it assigns the default value if the variable exists but evaluates to false:

// DO NOT USE
$v = @$v ?: 'default value';
SunnyRed

Just asked this and was pointed here. So in case you use a key of an array, this might be an improvement

function isset_get($array, $key, $default = null) {
    return isset($array[$key]) ? $array[$key] : $default;
}

Nope. That's the right way if you don't really know whether $v is set.

som

No way.If you use ternary operator.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!