C#'s null coalescing operator (??) in PHP

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';

PHP 7 adds the null coalesce 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.


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 .


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');
链接地址: http://www.djcxy.com/p/1740.html

上一篇: 什么是PHP中的“:”?

下一篇: PHP中C#的空合并运算符(??)