0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHP 関数呼び出し時に引数が指定されなかった場合のデフォルト値を設定する

Posted at

目的

関数呼び出しされる時に引数を指定しなかった時のデフォルト値を設定する方法をメモ的にまとめる

説明

  1. 下記のようなPHPの関数があったとする。

    public function foo($str_flag)
    {
        if (is_null($str_flag)) {
            echo "$str_flagにはnullが格納されています";
        } else {
            echo "$str_flagにはnull以外が格納されています"
        }
    }
    
  2. 上記の関数を実行する際に$str_flagを引数として渡さないとエラーになってしまう。

  3. 下記のように記載することで関数を実行する際に引数として$str_flagを渡さなかった場合にデフォルト値を設定することが出来る(下記はデフォルト値をnullとしている)

    public function foo($str_flag = null)
    {
        if (is_null($str_flag)) {
            echo "$str_flagにはnullが格納されています";
        } else {
            echo "$str_flagにはnull以外が格納されています"
        }
    }
    
  4. デフォルト値をtrueとしたいなら下記のように記載する。もちろんbool値以外もデフォルト値として設定することが可能である。

    public function foo($str_flag = true)
    
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?