LoginSignup
0
0

More than 3 years have passed since last update.

引数の記法

Last updated at Posted at 2020-08-17

引数のデフォルト値

cal1.php
function sum(float $a = 5, float $b = 2) : float {
      return $a + $b;
}

print sum(); // 7
print sum(1); // 3 $aに1が入る
print sum(1,5); // 6 $aに1,$bに5が入る

省略できるのは後ろの引数のみなので、要注意
引数にデフォルト値を設定できるのは、後方にデフォルト値のない引数がない場合のみ

cal2.php
function sum(float $a = 5, float $b) : float {
      return $a + $b;
}

print sum(5); // Error

可変長引数の関数

可変長引数の関数 = 引数の個数があらかじめ決まっていない関数

引数の前に「...」をつける

cal3.php
function sum(float ...$a) : float {
      $result = 0;
      foreach($a as $val){
          $result += $val;
      }
      return $result;
}

print sum(5,3,1); // 9
print sum(5,3,1,2); // 11

可変長引数は通常の引数と混合して使うことが可能。
この場合、可変長引数は引数リストの末尾に置かなければならない

参考文献

独習PHP第3版

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