Can I write a function in php with multiple optional arguments but at least one HAS to be used?
Solution:
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.
Answer
Solution:
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
}
//...
}
Answer
Solution:
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";
}
- Live demo at https://3v4l.org/i8qT0