Is this the standard behavior of PHP?
This works without warning:
function test($a)
{
echo 1;
}
test(2, 1);
This will cause warning:
functio开发者_如何学JAVAn test($a)
{
echo 1;
}
test();
If it's standard, any reason for this?
Because in the first example test()
may use func_get_args()
to access its arguments, so it shouldn't throw an error.
In the second example, the $a
is not optional. If you want it to be optional, tack a default in the arguments signature like so
function test($a = 1)
{
echo 1;
}
test();
So yes, it is default behaviour, and it makes sense once you know the above.
Concerning Edit
In the edited first example, you will be able to access 2
as $a
, however the 1
will only be accessible via func_get_args()
(or one of its similar functions like func_get_arg()
).
That is the correct behavior. Your function declaration states that it is expecting one argument. If you want to make a function argument optional, you should apply a default value. Otherwise you will raise an exception. Read the PHP documentation on Function Arguments for full details on how to declare your functions and the ways you can pass in values.
[Edit] This should work fine for you:
function test($a = null)
{
echo 1;
}
test();
I'm just speculating, but a function not receiving a parameter it's expecting is potentially more dangerous than a function receiving an extra parameter it can safely ignore.
Also, I wonder if it might have something to do with the fact that PHP will let you declare defaults for the parameter values, so the warning may be to prevent a situation where you've just forgotten to give $a a default
精彩评论