Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this the standard behavior of PHP?

Tags:

syntax

php

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?

like image 777
wamp Avatar asked Jun 30 '10 02:06

wamp


2 Answers

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

like image 153
alex Avatar answered Sep 22 '22 20:09

alex


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();
like image 36
Andrew Avatar answered Sep 22 '22 20:09

Andrew