Setting default values (conditional assignment)

有些话、适合烂在心里 提交于 2019-11-27 21:05:25

As of PHP 5.3 you can use the ternary operator while omitting the middle argument:

$x = $x ?: 'default';
isset($x) or $x = 'default';

As of PHP 7.0, you can also use the null coalescence operator

// PHP version < 7.0, using a standard ternary
$x = (isset($_GET['y'])) ? $_GET['y'] : 'not set';
//PHP version > 7.0
$x = $_GET['y'] ?? 'not set;
SeanDowney

I wrap it in a function:

function default($value, $default) {
    return $value ? $value : $default;
}
// then use it like:
$x=default($x, 'default');

Some people may not like it, but it keeps your code cleaner if you're doing a crazy function call.

I think your longer form is already the shortcut for php... and I wouldn't use it, because it is not good to read

Some notice: In the symfony framework most of the "get"-Methods have a second parameter to define a default value...

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