This works without warning:
function test($a)
{
echo 1;
}
test(2, 1);
This will cause warning:
function 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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With