【问题标题】:PHP non-falsy null coalesce operatorPHP 非假空合并运算符
【发布时间】:2016-11-15 10:39:29
【问题描述】:

当我发现 php7 的空合并运算符时,我非常高兴。但现在,在实践中,我发现它不是我想的那样:

$x = '';
$y = $x ?? 'something'; // assigns '' to $y, not 'something'

我想要 C# 的 ?? 运算符或 python 的 or 运算符:

x = ''
y = x or 'something' # assings 'something' to y

在 php 中有没有对应的简写形式?

【问题讨论】:

  • $y = $x ?: 'something';? $x 是否始终设置?
  • 如果您将它与 Python 的 or 进行比较... ?: 就是您想要的。否则,您必须澄清$x 是否保证存在,或者如果不存在,您是否需要避免错误。
  • 不,它可能在上下文中不可用。

标签: php operators


【解决方案1】:

不,PHP 没有非虚假的 null 合并运算符,但有一种解决方法。认识??0?:

<?php

$truly = true; // anything truly
$falsy = false; // anything falsy (false, null, 0, '0', '', empty array...)
$nully = null;

// PHP 7's "null coalesce operator":
$result = $truly ?? 'default'; // value of $truly
$result = $falsy ?? 'default'; // value of $falsy
$result = $nully ?? 'default'; // 'default'
$result = $undef ?? 'default'; // 'default'

// but because that is so 2015's...:
$result = !empty($foo) ? $foo : 'default';

// ... here comes...
// ... the "not falsy coalesce" operator!
$result = $truly ??0?: 'default'; // value of $truly
$result = $falsy ??0?: 'default'; // 'default'
$result = $nully ??0?: 'default'; // 'default'
$result = $undef ??0?: 'default'; // 'default'

// explanation:
($foo ?? <somethingfalsy>) ?: 'default';
($foo if set, else <somethingfalsy>) ? ($foo if truly) : ($foo if falsy, or <somethingfalsy>);

// here is a more readable[1][2] variant:
??''?:

// [1] maybe
// [2] also, note there is a +20% storage requirement

来源:
https://gist.github.com/vlakoff/890449b0b2bbe4a1f431

但请帮您的团队和您自己一个忙,“不要”。

【讨论】:

  • 我会选择 2015 版,非常感谢。除非您和代码库的每个未来贡献者每天都在使用 ??0?:,否则您将在 6 个月后摸不着头脑,试图弄清楚它在做什么。
  • 免责声明:我是该要点的作者,从那时起我已将其删除,因为正如您也理解的那样……请不要在您的代码中加入这种怪物!
  • 感谢@GrasDouble 为开发者的心理健康所做的贡献。
猜你喜欢
  • 2012-09-19
  • 2011-11-08
  • 2015-04-04
  • 2017-02-13
  • 2013-09-13
  • 1970-01-01
  • 2015-03-27
  • 2023-03-23
  • 2012-09-23
相关资源
最近更新 更多