LoginSignup
3
1

More than 1 year has passed since last update.

実務でよく使うPHP8系 文法

Posted at

PHP8がリリースされてから
なんだかんだ実務でよく使う新文法を羅列しました

名前付き引数

    function funcA(
        int $hoge = 0,
        int $fuga = 0,
        int $foo = 0,
        int $bar = 0,
        int $buzz = 0
    ) {
    }

    $this->funcA(foo: 20, fuga:3);

コンストラクタでの、プロパティのプロモーション

    public function __construct(
        protected Staff $staff,
        protected Customer $customer
    ) {
    }

    // これだけで下記を書いたことになる
    // $this->staff = $staff;
    // $this->customer = $customer;

Nullsafe 演算子

下記はLaravelの場合です

$user = User::whereNotNull('name')
->get()
?->toArray()

// Laravelのクエリビルダーに生えるget()は
// 検索にヒットすればEloquentCollection
// 検索にヒットしなかった場合nullを返してくるので
// 検索結果に依存してtoArray()が実行できるか変わってくる。

// nullのチェックのifを書くのも面倒なので、
// Nullsafe 演算子をtoArray()に付けることで
// $userがnull or 配列かを得ることができる

最後に

PHP8.1の機能を使えてないなーと思ったりしてます。
せっかくの新機能なので使わないともったいない!
そこはチャレンジでバンバン使っていきたい気持ちです!

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