1

I have a function that look like this:

function test($arg1 = 'my_value', $arg2 = 'second')
{
}

When I call it I only want to set the second value to something different, like this:

test(inherit, 'changed value');

I found out that it is possible to add this line to my function (when my "inherit" is changed to null):

$arg1 = ( is_null( $arg1 ) ? 'my_value' : $arg1 );

Is there a better way, a nicer way to solve it?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206

4 Answers4

2

Depending on the nature and number of your parameters it may be reasonable to use named parameters (at least emulated):

function xyz($args) {
    $args += array(
        'x' => 'default',
        'q' => 'default 2',
        // ...
    );

    // ...
}

xyz(array('q' => 'hehe, not default'));
NikiC
  • 100,734
  • 37
  • 191
  • 225
  • Seems like this is the best suggestion. Not perfect but it seems like there is no better way at the moment. Thanks! – Jens Törnell May 15 '11 at 12:18
  • 1
    An idea is to use `extract($args)` inside `xyz` . That way, you can use `$q` instead of `$args['q']`. – alexn May 15 '11 at 15:20
1

The way you have solved it is actually pretty usable.

The other way is to pass the same value as the default value every time on the function call.

If that is structural, then you have to reconsider the function.

Sander
  • 1,244
  • 1
  • 12
  • 24
1

Make two different functions:

// Full function
function testex($arg1 = 'my_value', $arg2 = 'second')
{
}

// Shorthand when just argument 2 is needed
function test2($arg2 = 'second')
{
  return testex('my_value', $arg2);
}

That way, you don't have to pass null to the first parameter when you don't need to.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
0

You will have to flip them, you can't leave the first value to be blank,

Set the first value and let the second one be the default value;

UPDATE:

If you want to have dynamic length to your argument consider using the func_get_args();

function something() {
    $args = func_get_args();
  ....
}

then you can test your arguments for different value or datatype to make them do whatever yuo please

Ibu
  • 42,752
  • 13
  • 76
  • 103
  • Not good enough. In my real function there are more values than these. I can't just switch them to try to ignore the problem. In other cases I want to do the opposite. – Jens Törnell May 15 '11 at 08:47