3
0

PHP nullsafe演算子(?->)について

Last updated at Posted at 2022-05-30

概要

  • 実務でnullsafe演算子を使う事があったのでどういうものかまとめておく。

nullsafe演算子

  • nullsafe演算子は下記である。

    ?->
    
  • 下記の様なコードがあったとする。

    if (is_null($repository)) {
        $result = null;
    } else {
        $user = $repository->getUser(5);
        if (is_null($user)) {
            $result = null;
        } else {
            $result = $user->name;
        }
    }
    
  • 下記の様な処理になっている。

    • $repositoryがnullのときnullを$resultに格納する。
    • $repositoryがnullではないかつ、$repository->getUser(5)がnullのときnullを$resultに格納する。
    • $repositoryがnullではないかつ、$repository->getUser(5)がnullじゃないとき$user->name$resultに格納する。
  • PHP8からのnullsafe演算子を用いると下記の様に記載する事ができるらしい。(nullsafe演算子の左側の値がnullの時にそれ以降処理を実行せずnullを返す。)

    $result = $repository?->getUser(5)?->name;
    
  • nullsafe演算子を用いることで複雑な記載を1行で記載する事ができる。

参考文献

3
0
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
0