15

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
matthy
  • 8,144
  • 10
  • 38
  • 47

5 Answers5

25

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'));
kouak
  • 773
  • 6
  • 17
  • 2
    Peh, beat me to it. Being an example, `extract` is fine but for real world use, there is no need to declare that many variables. Just wanted to note ;) – phidah Oct 25 '09 at 12:24
10

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.

Joost
  • 10,333
  • 4
  • 55
  • 61
2

The parameters with default values have to be last, after the others, in PHP and all the others up to that point must be filled in when calling the function. I don't know of anyway to pass a value that triggers the default value.

JAL
  • 21,295
  • 1
  • 48
  • 66
1

What I normally do in those situations is to specify the parameters as an array instead. Have a look at the following example (untested):

<?php
test(array('t3' => 'something'));

function test($options = array())
{
  $default_options = array('t1' => 'test1', 't2' => 'test2', 't3' => 'test3');
  $options = array_merge($default_options, $options);

  echo $options['t1'] . ', ' . $options['t2'] . ', ' . $options['t3'];
}
?>
phidah
  • 5,794
  • 6
  • 37
  • 58
0

you could define the function like:

function grafico($valores,$img_width=false,$img_height=false,$titulo="title"){
    if ($img_width===false){$img_width=450;}
    if ($img_height===false){$img_height=300;}
    ...
   }

and call to it without the lasting params or replacing one or several with "false":

grafico($values);
grafico($values,300);
grafico($values,false,400);
grafico($values,false,400,"titleeee");
Martijn
  • 15,791
  • 4
  • 36
  • 68