0
1

More than 3 years have passed since last update.

【PHP】関数のnullable宣言は デフォルト値(= null)ではなくハテナ(?)を使おう

Posted at

はじめに

こんにちは。ブログいろいろいじっていたらAMPページが壊れて、いろいろ大変な事態になってしまいました、筆者です :innocent:

さて、今回はPHP 8.0.0から非推奨になった機能をご紹介しようと思います。

これ見たことないですか?

というか超お世話になってますし、よく見るし、よく書いてました :sweat:

以下test関数使用時には、引数を渡さないで実行した場合は、デフォルト値のnull$aに代入されて処理されます。
nullをデフォルト値とすることで、型が暗黙のうちにnullableであることを示しています。

<?php
    function test(string $a = null) {} // 非推奨

推奨される書き方

素直にnullableと表記します。

<?php
    function test(?string $a) {} // 推奨

おわりに

この機に改めて自分の書いたコード見返したら、以下のようになっていて、両方書いておりました :bow: :bow: :bow:

<?php
    function test(?string $a = null) {}

これはこれでよくないですね...。ちゃんと理解せず書いておりました。
以後気を付けます:pray:

それでは!

参考文献

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