2

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

  • 1 name 1000

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

  • name 1 given salary
  • 5
    You can't - how is PHP to know that it's the second one you want to skip, and not the third? If you want to do this, I'd suggest tweaking the function so it accepts an associative array of named parameters, so you can just pass in the ones that you want. – andrewsi Dec 20 '13 at 13:21
  • http://stackoverflow.com/questions/1620737/using-default-value-when-calling-a-function this is exactly what you need –  Dec 20 '13 at 13:23
  • Also you can explore this http://stackoverflow.com/questions/9166914/php-using-default-arguments-in-a-function –  Dec 20 '13 at 13:26
  • Why don't you set the default values to something like `NULL` and check for that in the function before you use them? – jeroen Dec 20 '13 at 13:32
  • 2
    You should not do this at all,.. try proper objects and getter setter will safe you much time when you want to extend the project later + the inputs can be way better validated – Daniel W. Dec 20 '13 at 13:37

3 Answers3

3

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);
    }
    
Kevin
  • 1,000
  • 2
  • 10
  • 31
0

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.

bishop
  • 37,830
  • 11
  • 104
  • 139
0

A second function will do the job.

function second($name,$another){
  first( $name ,1,$another);
}
Eduardo Stuart
  • 2,869
  • 18
  • 22