This question already has an answer here:
I have a function with a known number of parameters like
function myFunction($name, $id=1,$salary=1000) {
echo $id;
echo $name;
echo $salary
}
when i call this function
myFunction("name");
it displays
But How I can ignore the id
parameter of this function and want to give 1st and 3rd arguments only? like
myfunction("name",ignore 2nd parameter and give value of 3rd parameter)
so that it should display
</div>
You can't with native code. Two solutions :
Take an array of parameters like that :
function myFunction($params) {
if (!isset($params['name'])) throw new Exception();
if (!isset($params['id'])) $params['id'] = 1;
if (!isset($params['salary'])) $params['salary'] = 1000;
echo $params['id'];
echo $params['name'];
echo $params['salary'];
}
Create a new function myFunction2
:
function myFunction2($name, $salary) {
return myFunction($name, 1, $salary);
}
Variable argument function?
function myFunction() {
switch (func_num_args()) {
case 2:
$name = func_get_arg(0);
$salary = func_get_arg(1);
break;
case 3:
$name = func_get_arg(0);
$id = func_get_arg(1);
$salary = func_get_arg(2);
break;
default:
throw new Exception();
}
}
myFunction('name', 1000);
myFunction('name', 1, 2000);
If you wanted to set defaults for these, then you would do that inside the switch statement.
I'm not advocating this as a good solution, but it is a solution.
A second function will do the job.
function second($name,$another){
first( $name ,1,$another);
}