Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php function arguments

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
like image 695
Clint C. Avatar asked Dec 21 '22 23:12

Clint C.


1 Answers

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
}
like image 167
Starx Avatar answered Jan 02 '23 14:01

Starx