tags:

views:

106

answers:

3

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?

+15  A: 

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()).

alex
I changed a little so that you guys shouldn't focus on the function not receiving a parameter
wamp
@wamp Not sure what your edit changes. This answer still stands.
ceejayoz
+1 for reference to func_get_args()
Mark Baker
A: 

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

Rob Cooney
+1  A: 

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();
Andrew