Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip arguments when their default is desired [duplicate]

Tags:

php

If I have a function like this:

function abc($a,$b,$c = 'foo',$d = 'bar') { ... }

And I want $c to assume it's default value, but need to set $d, how would I go about making that call in PHP?

like image 296
Alex S Avatar asked Jul 12 '09 01:07

Alex S


People also ask

CAN default arguments be skipped?

It's not possible to skip it, but you can pass the default argument using ReflectionFunction .

How do you omit an argument in Python?

You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.

CAN default arguments be skipped from a function call?

Default arguments can be skipped from function call​.

Which type of parameter may be skipped while calling a function?

During a function call, only giving mandatory argument as a keyword argument. Optional default arguments are skipped.


1 Answers

PHP can't do this, unfortunately. You could work around this by checking for null. For example:

function abc($a, $b, $c = 'foo', $d = 'bar') {
    if ($c === null)
        $c = 'foo';
    // Do something...
}

Then you'd call the function like this:

abc('a', 'b', null, 'd');

No, it's not exactly pretty, but it does the job. If you're feeling really adventurous, you could pass in an associative array instead of the last two arguments, but I think that's way more work than you want it to be.

like image 78
Sasha Chedygov Avatar answered Oct 13 '22 18:10

Sasha Chedygov