39
16

More than 5 years have passed since last update.

PHPは引数が足りないときはエラーになるが、引数が多いぶんには何も言わない

Last updated at Posted at 2019-01-18

PHPは関数の引数が足りないときは、Fatalエラーを出すが、引数が多いぶんにはエラー等にはならず、そのまま処理が進む仕様がある。

関数の引数が足りないとき:

function dyadic_function($arg1, $arg2): void
{
    // do nothing
}

dyadic_function(1);

出力結果:

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function dyadic_function(), 1 passed in Test.php on line 8 and exactly 2 expected in Test.php:3

関数の引数が多いとき:

function dyadic_function($arg1, $arg2): void
{
    // do nothing
}

dyadic_function(1, 2, 3);
echo 'OK';

出力結果:

OK

ちなみに、上記の再現コードはGitHubに置いておいた。

引数を多く渡すコードは実行しても気づけないことがあるので、PhpStormを使ってコーディング中に分かるようにしておく。これがまずは手頃にできる対応だろう。

PhpStormが問題点を警告する様子:

php-playground___Volumes_dev_php-playground__-___Library_Preferences_PhpStorm2018_3_scratches_scratch_4_php.png

39
16
2

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
39
16