将变量传递给 PHP 中的函数 [英] Passing variables to functions in PHP

查看:30
本文介绍了将变量传递给 PHP 中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 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');

我知道,我们可以很容易地将它传递为 func_name('jack', 'Brazil'); 但上面的函数只是一个例子.实际的函数有大约 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($name = 'Jack', $country = 'Brazil');

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

推荐答案

不,这不是正确的方法.foo($bar = 'baz') 意味着您像往常一样将 'baz' 分配给变量 $bar.这个赋值操作的结果是被赋值的值,所以表达式$bar = 'baz'的值为'baz'.这个 value 'baz' 被传递到函数中.这些函数没有任何线索表明您已分配给变量 $bar.

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 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆