More parameter than expected: no error in PHP?

2020-04-27 07:39发布

问题:

Please see this code, where I pass more parameters than expected to a custom function:

error_reporting(E_ALL);
ini_set("display_errors", 1);

daidai("asassa", "asgfasfas", "asassa");

function daidai($aa)
{
    echo $aa;
}

This doesn't emit an error at all, while I was expecting Warning: function daidai() expects at most 1 parameter, 3 given

What puzzles me is that this emits said error as expected:

$Odate=new DateTime();
$sfasfasf=$Odate->setTime("23", "59", "30", "unexpected");

Why?

回答1:

That is because the setTime() method itself performs a check on the number of parameters, if you want it in your functions, you have to implement it yourself.

For reference you might look into the docs for func_num_args(), func_get_arg() and func_get_args()

From the docs:

No special syntax is required to note that a function is variadic; however access to the function's arguments must use func_num_args(), func_get_arg() and func_get_args().

Hence, php really treats every function as a variadic one.