问题描述
我有以下PHP函数:
function func_name($name = 'John', $country = 'USA')
{
do something;
}
而现在,我试图通过变量的函数如下:
And now, am trying to pass variable to the function as follows:
FUNC_NAME($名='杰克',$国家='巴西');
我知道,我们可以很容易地把它作为 FUNC_NAME('杰克','巴西');
,但上述功能仅仅是一个例子。实际的功能,有大约20个参数,所有有默认值,有的不是在所有传递给函数
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
所以,我想知道,如果它的正确传递参数为 FUNC_NAME($名='杰克',$国家='巴西');
So I would like to know if its proper to pass arguments as func_name($name = 'Jack', $country = 'Brazil');
推荐答案
没有,这不是正确的做到这一点的方式。 富($栏='巴兹')
意味着你分配巴兹
来变量 $栏
如常。这的赋值运算的结果值已分配,所以除权pression $栏='巴兹'
值为巴兹
。这的值的巴兹
被传递给函数。该功能没有任何线索,已分配给一个变量 $栏
。
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
.
在换句话说,PHP不支持命名的参数。
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'));
这篇关于传递变量函数在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!