开发者

Passing variables to functions in PHP

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');


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'));


Could you pass in an array?

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜