Passing variables to functions in PHP

雨燕双飞 提交于 2020-01-02 21:25:25

问题


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:


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



回答2:


Could you pass in an array?

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


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


来源:https://stackoverflow.com/questions/6562506/passing-variables-to-functions-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!