isset() 的 PHP 简写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18603250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:54:11  来源:igfitidea点击:

PHP shorthand for isset()?

phpissetshorthand

提问by brentonstrine

Is there a shorthand way to assign a variable to something if it doesn't exist in PHP?

如果某个变量在 PHP 中不存在,是否有一种速记方法可以将其分配给某个变量?

if(!isset($var) {
  $var = "";
}

I'd like to do something like

我想做类似的事情

$var = $var | "";

回答by hek2mgl

Update for PHP 7(thanks shock_gone_wild)

PHP 7 更新(感谢shock_gone_wild

PHP 7 introduces the so called null coalescing operatorwhich simplifies the below statements to:

PHP 7 引入了所谓的空合并运算符,它将以下语句简化为:

$var = $var ?? "default";

Before PHP 7

PHP 7 之前

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

不,这没有特殊的运算符或特殊的语法。但是,您可以使用三元运算符:

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

Or like this:

或者像这样:

isset($var) ?: $var = 'default';

回答by Fabien Sa

PHP 7.4+; with the null coalescing assignment operator

PHP 7.4+; 使用空合并赋值运算符

$var ??= '';

PHP 7.0+; with the null coalescing operator

PHP 7.0+; 使用空合并运算符

$var = $var ?? '';

PHP 5.3+; with the ternary operatorshorthand

PHP 5.3+; 使用三元运算符速记

isset($var) ?: $var = '';

Or for all/older versionswith isset:

或者对于带有isset 的所有/旧版本

$var = isset($var) ? $var : '';

or

或者

!isset($var) && $var = '';