1

I have the following PHP function:

 function func_name($name = 'John', $country = 'USA')
  {
  do something;
  }

And now, am trying to pass variable to the function as follows:

func_name($name = 'Jack', $country = 'Brazil');

I know, we can pass it easily as func_name('jack', 'Brazil'); but the above function is just an example. The actual function has around 20 arguments and all have default values, and some are not at all passed to the function

So I would like to know if its proper to pass arguments as func_name($name = 'Jack', $country = 'Brazil');

1
  • The elegant solution would be to pass these variables in an array and then,assign the variables their desired values in your called function. Commented Jul 3, 2011 at 11:07

2 Answers 2

5

No, it's not the right way to do it. foo($bar = 'baz') means you're assigning 'baz' to the variable $bar as usual. This assignment operation results in the value that was assigned, so the expression $bar = 'baz' has the value 'baz'. This value 'baz' gets passed into the function. The functions doesn't have any clue that you have assigned to a variable $bar.

In other words, PHP doesn't support named arguments.

If your function accepts many parameters, all or most of which are optional, use arrays:

function foo(array $args = array()) {
    // set default values for arguments not supplied
    $args += array('name' => 'John', 'country' => 'USA', …);

    // use $args['name'] etc.
    // you could do extract($args), then use $name directly,
    // but take care not to overwrite other variables

}

foo(array('country' => 'Japan'));
Sign up to request clarification or add additional context in comments.

Comments

5

Could you pass in an array?

function something($arr) {
    $name = $arr['name'];
}


function something(Array("name"=>"jack", "country"=>"UK"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.