Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP have "named parameters" so that early arguments can be omitted and later arguments can be written? [duplicate]

In PHP you can call a function with no arguments passed in so long as the arguments have default values like this:

function test($t1 ='test1',$t2 ='test2',$t3 ='test3')
{
    echo "$t1, $t2, $t3";
}
test();

However, let's just say I want the last one to be different but the first two parameters should use their default values. The only way I can think of is by doing this with no success:

test('test1','test2','hi i am different');

I tried this:

test(,,'hi i am different');
test(default,default,'hi i am different');

Is there clean, valid way to do this?

like image 605
matthy Avatar asked Oct 25 '09 12:10

matthy


People also ask

Does PHP support named parameters?

As stated in the other answers, PHP does not directly support named parameters.

Do parameter names and argument names have to be the same?

The caller's arguments passed to the function's parameters do not have to have the same names.

What are arguments and parameters in PHP?

PHP Function ArgumentsAn argument is just like a variable. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

How many arguments can be passed to a function in PHP?

PHP native functions According to the manual, PHP functions may accept up to 12 arguments.


2 Answers

Use arrays :

function test($options = array()) {
    $defaults = array(
        't1' => 'test1',
        't2' => 'test2',
        't3' => 'test3',
    );
    $options = array_merge($defauts, $options);
    extract($options);
    echo "$t1, $t2, $t3";
}

Call your function this way :

test(array('t3' => 'hi, i am different'));
like image 50
kouak Avatar answered Oct 01 '22 00:10

kouak


You can't do that using raw PHP. You can try something like:

function test($var1 = null, $var2 = null){
    if($var1 == null) $var1 = 'default1';
    if($var2 == null) $var2 = 'default2';
}

and then call your function, with null as the identifier of the default variable. You can also use an array with the default values, that will be easier with a bigger parameter list.

Even better is to try to avoid this all, and rethink your design a bit.

like image 37
Joost Avatar answered Oct 01 '22 01:10

Joost