52

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

6 に答える 6

69

PHP 7は、null合体演算子を追加します。

// 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#では、存在しない配列/辞書アイテムにアクセスしようとすると、ランタイムエラーも発生します。

于 2011-09-02T03:00:08.950 に答える
52

Null 合体演算子( ??) が受け入れられ、PHP 7 で実装されまし。これは、キーを持たない配列にアクセスしようとしたときに発生するを抑制するという点で、短い三項演算子( ?:)とは異なります。RFC の最初の例は次のとおりです。??E_NOTICE

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

オペレータは、を防ぐために を??手動で適用する必要がないことに注意してください。issetE_NOTICE

于 2014-10-01T13:39:15.113 に答える
10

関数を使用しています。明らかにそれは演算子ではありませんが、あなたのアプローチよりもきれいに見えます:

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

使用法:

isset_or($_REQUEST['test'],'hi');
于 2013-09-08T16:22:15.217 に答える
6

PHP 7より前は、ありません。関与する必要がある場合isset、使用するパターンはですisset($var) ? $var : null?:の特性を含む演算子はありませんisset

于 2011-09-02T03:03:17.860 に答える
4

??C#では2進数であり、3進数ではありません。また、PHP7より前のPHPでは同等のものはありません。

于 2011-09-02T03:02:39.950 に答える
1

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に設定するという副作用があります。これは、配列のサイズまたは真実性が重要な場合に問題になる可能性があります。

于 2013-07-14T00:34:46.583 に答える