LoginSignup
3
2

More than 3 years have passed since last update.

php7.0からの新機能null合体演算子の使い方

Posted at

php7系は5.6からメジャーバージョンとして大幅に変更されていますが、
タイプヒンティングなど有意義なものが多いです。

null合体演算子はその中でも便利な新機能です。

null合体演算子

phpはissetやempty、is_nullなどの型判定がありますが
isset()と三項演算子を組み合わせたパターンはよくあると思います。

$hoge = 'a';
$test = isset($hoge) ? $hoge : 'other';
var_dump($test);

これを

$hoge = 'a';
$test = $hoge ?? 'other';
var_dump($test);

$hoge = null;
$test = $hoge ?? 'other';
var_dump($test);

と書くことができます。

出力結果
ーーーーー
string(1) "a"
string(5) "other"

スッキリしたコードになるので地味にとても便利です。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2