2016-11-15 19 views
2

php7のヌル合体演算子について知ったとき、とてもうれしかったです。しかし、今、実際には、私はそれが私はそれが考えたものではありませんことを参照してください。PHPの偽のヌル合体演算子

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

私はC#の??オペレータやPythonのorオペレータのいずれかのような何かしたい:

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

は、任意の短い手がありますPHPのこれと同等ですか?

+0

'$ yを= $ xに:? '何か';'? '$ x'はいつも設定されていますか? –

+0

もしそれをPythonの 'or' ...' ':' 'と比較するなら、あなたが望むものです。さもなければ '$ x'が存在することが保証されているかどうか、もしそうでなければエラーを避ける必要があるかどうかを明確にしなければなりません。 – deceze

+0

いいえ、それは文脈で利用できないかもしれません。 –

答えて

2

いいえ、PHPには偽のヌル結合演算子はありませんが、回避策があります。ミート??0?:

<?php 

$truly = true; // anything truly 
$false = 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

+1

私は2015バージョン、thankyouverymuchと一緒に行きます。あなたとコードベースの今後のすべての貢献者が毎日「?? 0?:」を使用している場合を除いて、あなたは何をしているのかを把握しようとすると、あなたの頭を6ヶ月掻き回します。 – deceze

+1

私は個人的にはそれもとても読めないと思います。 – sepehr