I don't know how or where I got this idea in my head but for some reason I thought this was possible. Obviously after testing it doesn't work, but is there a way to make it work? I want to set $value2 without having to enter anything at all for $value1.
function test($value1 = 1, $value2 = 2) {
echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';
}
test($value2 = 3);
// output
Value 1: 3
Value 2: 2
Its not entirely possible the way you want.
Simply,
function test($value1 = null, $value2 = 2) {
echo 'Value 1: '.$value1.'<br />';
echo 'Value 2: '.$value2.'<br />';
}
test(NULL, $value2 = 3);
Or, Use array as parameters
function test($array) {
if(isset($array['value1'])) echo 'Value 1: '.$array['value1'].'<br />';
if(isset($array['value2'])) echo 'Value 2: '.$array['value2'].'<br />';
}
test(array('value2' => 3));
Update:
My another attempt
function test() {
$args = func_get_args();
$count = count($args);
if($count==1) { test1Arg($args[0]); }
elseif($count == 2) { test2Arg($args[0],$args[1]); }
else { //void; }
}
function test1Arg($arg1) {
//Do something for only one argument
}
function test2Arg($arg1,$arg2) {
//Do something for two args
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With