PHP 中的 C# 空合并运算符 (??)

发布于 2024-12-02 11:32:10 字数 461 浏览 1 评论 0原文

PHP中有没有类似C#的??的三元运算符之类的?

C# 中的 ?? 干净且较短,但在 PHP 中您必须执行以下操作:

// This is absolutely okay except that $_REQUEST['test'] is kind of redundant.
echo isset($_REQUEST['test'])? $_REQUEST['test'] : 'hi';

// This is perfect! Shorter and cleaner, but only in this situation.
echo null? : 'replacement if empty';

// This line gives error when $_REQUEST['test'] is NOT set.
echo $_REQUEST['test']?: 'hi';

Is there a ternary operator or the like in PHP that acts like ?? of C#?

?? in C# is clean and shorter, but in PHP you have to do something like:

// This is absolutely okay except that $_REQUEST['test'] is kind of redundant.
echo isset($_REQUEST['test'])? $_REQUEST['test'] : 'hi';

// This is perfect! Shorter and cleaner, but only in this situation.
echo null? : 'replacement if empty';

// This line gives error when $_REQUEST['test'] is NOT set.
echo $_REQUEST['test']?: 'hi';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

陈独秀 2024-12-09 11:32:10

PHP 7 添加了 空合并运算符

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

您还可以查看编写 PHP 三元运算符 ?: (仅限 PHP >=5.3)

// Example usage for: Short Ternary Operator
$action = $_POST['action'] ?: 'default';

// The above is identical to
$action = $_POST['action'] ? $_POST['action'] : 'default';

并且您与 C# 的比较是不公平的。 “在 PHP 中你必须做类似的事情” - 在 C# 中,如果你尝试访问不存在的数组/字典项,你也会遇到运行时错误。

PHP 7 adds the null coalescing operator:

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

You could also look at short way of writing PHP's ternary operator ?: (PHP >=5.3 only)

// Example usage for: Short Ternary Operator
$action = $_POST['action'] ?: 'default';

// The above is identical to
$action = $_POST['action'] ? $_POST['action'] : 'default';

And your comparison to C# is not fair. "in PHP you have to do something like" - In C# you will also have a runtime error if you try to access a non-existent array/dictionary item.

£烟消云散 2024-12-09 11:32:10

空合并运算符,(??) 已在 PHP 7。它不同于 短三元运算符 (? :) 中的 ?? 将抑制 E_NOTICE ,否则在尝试访问没有键的数组时会发生这种情况。 RFC 中的第一个示例给出:

$username = $_GET['user'] ?? 'nobody';
// equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

请注意,?? 运算符不需要手动应用 isset 来防止 E_NOTICE

The Null Coalesce Operator, (??) has been accepted and implemented in PHP 7. It differs from the short ternary operator (?:) in that ?? will suppress the E_NOTICE that would otherwise occur when attempting to access an array where it doesn't have a key. The first example in the RFC gives:

$username = $_GET['user'] ?? 'nobody';
// equivalent to: $username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

Notice that the ?? operator does not require the manual application of isset to prevent the E_NOTICE.

陌上芳菲 2024-12-09 11:32:10

我用的是函数。显然它不是运算符,但看起来比你的方法更干净:

function isset_or(&$check, $alternate = NULL)
{
    return (isset($check)) ? $check : $alternate;
}

用法:

isset_or($_REQUEST['test'],'hi');

I use function. Obviously it is not operator, but seems cleaner than your approach:

function isset_or(&$check, $alternate = NULL)
{
    return (isset($check)) ? $check : $alternate;
}

Usage:

isset_or($_REQUEST['test'],'hi');
彩虹直至黑白 2024-12-09 11:32:10

在 PHP 7 之前,没有。如果您需要涉及 isset,则使用的模式是 isset($var) ? $var:空。没有包含 isset 特征的 ?: 运算符。

Prior to PHP 7, there isn't. If you need to involve isset, the pattern to use is isset($var) ? $var : null. There's no ?: operator that includes the characteristics of isset.

为你拒绝所有暧昧 2024-12-09 11:32:10

?? 在 C# 中是二进制的,而不是三进制的。在 PHP 7 之前的 PHP 中,它没有等效项。

?? is binary in C#, not ternary. And it has no equivalence in PHP prior to PHP 7.

青萝楚歌 2024-12-09 11:32:10

从 PHP 5.6 开始,不存在相同的运算符,但您可以创建一个行为类似的函数。

/**
 * Returns the first entry that passes an isset() test.
 *
 * Each entry can either be a single value: $value, or an array-key pair:
 * $array, $key.  If all entries fail isset(), or no entries are passed,
 * then first() will return null.
 *
 * $array must be an array that passes isset() on its own, or it will be
 * treated as a standalone $value.  $key must be a valid array key, or
 * both $array and $key will be treated as standalone $value entries. To
 * be considered a valid key, $key must pass:
 *
 *     is_null($key) || is_string($key) || is_int($key) || is_float($key)
 *         || is_bool($key)
 *
 * If $value is an array, it must be the last entry, the following entry
 * must be a valid array-key pair, or the following entry's $value must
 * not be a valid $key.  Otherwise, $value and the immediately following
 * $value will be treated as an array-key pair's $array and $key,
 * respectfully.  See above for $key validity tests.
 */
function first(/* [(array $array, $key) | $value]... */)
{
    $count = func_num_args();

    for ($i = 0; $i < $count - 1; $i++)
    {
        $arg = func_get_arg($i);

        if (!isset($arg))
        {
            continue;
        }

        if (is_array($arg))
        {
            $key = func_get_arg($i + 1);

            if (is_null($key) || is_string($key) || is_int($key) || is_float($key) || is_bool($key))
            {
                if (isset($arg[$key]))
                {
                    return $arg[$key];
                }

                $i++;
                continue;
            }
        }

        return $arg;
    }

    if ($i < $count)
    {
        return func_get_arg($i);
    }

    return null;
}

用法:

$option = first($option_override, $_REQUEST, 'option', $_SESSION, 'option', false);

这将尝试每个变量,直到找到满足 isset() 的变量:

  1. $option_override
  2. $_REQUEST['option']
  3. $_SESSION['option']
  4. false

如果 4 不存在,则默认为 null

注意:有一个使用引用的更简单的实现,但它具有 将测试项设置为 null(如果尚未设置为 null)的副作用存在。当数组的大小或真实性很重要时,可能会出现问题

An identical operator doesn't exist as of PHP 5.6, but you can make a function that behaves similarly.

/**
 * Returns the first entry that passes an isset() test.
 *
 * Each entry can either be a single value: $value, or an array-key pair:
 * $array, $key.  If all entries fail isset(), or no entries are passed,
 * then first() will return null.
 *
 * $array must be an array that passes isset() on its own, or it will be
 * treated as a standalone $value.  $key must be a valid array key, or
 * both $array and $key will be treated as standalone $value entries. To
 * be considered a valid key, $key must pass:
 *
 *     is_null($key) || is_string($key) || is_int($key) || is_float($key)
 *         || is_bool($key)
 *
 * If $value is an array, it must be the last entry, the following entry
 * must be a valid array-key pair, or the following entry's $value must
 * not be a valid $key.  Otherwise, $value and the immediately following
 * $value will be treated as an array-key pair's $array and $key,
 * respectfully.  See above for $key validity tests.
 */
function first(/* [(array $array, $key) | $value]... */)
{
    $count = func_num_args();

    for ($i = 0; $i < $count - 1; $i++)
    {
        $arg = func_get_arg($i);

        if (!isset($arg))
        {
            continue;
        }

        if (is_array($arg))
        {
            $key = func_get_arg($i + 1);

            if (is_null($key) || is_string($key) || is_int($key) || is_float($key) || is_bool($key))
            {
                if (isset($arg[$key]))
                {
                    return $arg[$key];
                }

                $i++;
                continue;
            }
        }

        return $arg;
    }

    if ($i < $count)
    {
        return func_get_arg($i);
    }

    return null;
}

Usage:

$option = first($option_override, $_REQUEST, 'option', $_SESSION, 'option', false);

This would try each variable until it finds one that satisfies isset():

  1. $option_override
  2. $_REQUEST['option']
  3. $_SESSION['option']
  4. false

If 4 weren't there, it would default to null.

Note: There's a simpler implementation that uses references, but it has the side effect of setting the tested item to null if it doesn't already exist. This can be problematic when the size or truthiness of an array matters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文