viamonster
viamonster

Reputation: 27

Can I write a function in php with multiple optional arguments but at least one HAS to be used?

I'm still new to PHP, so I wonder if it is possible to write a function with several optional parameters but at least one of those needs to be used?

Something like

function my_func($arg1="", $arg2="", $arg3=""){
//at least one of the args should be set
}

or do I just test within in the function and return false if none was set?

Upvotes: 2

Views: 347

Answers (3)

Nigel Ren
Nigel Ren

Reputation: 57121

You could add code yourself which you can always enhance to check (for example) only 1 argument should be passed. Just throw InvalidArgumentException with some description if the validation fails...

function my_func($arg1="", $arg2="", $arg3=""){
    if ( empty($arg1) && empty($arg2) && empty($arg3) ) {
        throw new InvalidArgumentException("At least one parameter must be passed");
    }
}

You may want to set the default values to null if "" is a valid value, but then change the test to is_null($arg1) etc. as "" is also empty.

Upvotes: 2

Qirel
Qirel

Reputation: 26450

You would have to explicitly check it within the function body, but you can streamline it a little by pushing all your variables to an array, and filter the empty values out. When there are no results left after filtering, you know none was passed.

function my_func($arg1 = null, $arg2 = null, $arg3 = null) {
    if (count(array_filter([$arg1, $arg2, $arg3])) === 0) {
        throw new InvalidArgumentException('At least one argument must be used');
    }
    echo 'It works!'."\n";
}

Upvotes: 2

nikserg
nikserg

Reputation: 382

You should check it manually. Like this

function my_func($arg1="", $arg2="", $arg3=""){
 if (!$arg1 && !$arg2 && !$arg3) {
   throw new Exception('None of arguments is set!'); //Or just return false, depend on your siruation
 }
 //...
}

Upvotes: 2

Related Questions