函数中的可变长度 by-ref 参数列表
在 PHP 中,你可以这样做:
function something() {
foreach (func_get_args() as $arg)
echo $arg;
}
something(1, 3); //echoes "13"
这对于按值传递的参数来说效果很好,但如果我希望它们按引用传递怎么办?像这样:
function something_else() {
foreach (func_get_args() as $arg)
$arg *= 2;
}
$a = 1;
$b = 3;
something_else($a, $b);
echo $a . $b; //should echo "26", but returns "13" when I try it
这在 PHP 中可能吗?
In PHP you can do this:
function something() {
foreach (func_get_args() as $arg)
echo $arg;
}
something(1, 3); //echoes "13"
This works fine for arguments passed by value, but what if I want them to be passed by reference? like this:
function something_else() {
foreach (func_get_args() as $arg)
$arg *= 2;
}
$a = 1;
$b = 3;
something_else($a, $b);
echo $a . $b; //should echo "26", but returns "13" when I try it
Is this possible in PHP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个问题看起来很可怕,但让你幽默一下。下面是一个可怕的黑客,但您可以发送一个包含您想要使用的项目的参数。
The question seems horrible, but lets humour you. Below is a horrible hack, but you could send across a single argument which contains the items that you want to work with.
不,你不能。由 ref 传递的参数的声明显式为
function Something(&$arg1, &$arg2)
。如果您在编译时不知道参数的数量,可以执行以下操作:基本上,代码将函数将修改的参数名称传递给函数。
$GLOBALS
保存对脚本全局范围内所有已定义变量的引用。这意味着如果调用来自另一个函数,它将不起作用:触发器会注意到未定义的索引
a
和b
。因此,另一种方法是创建一个数组,其中引用函数将修改的变量,如下所示:注意
foreach
行上的&
。这是需要的,这样就不会创建一个迭代数组的新变量。 PHP>此功能需要 5 个。No. You cannot. The declaration of a prameter passed by ref is explicit as
function something(&$arg1, &$arg2)
. If you don't know the number of parameters at compile time, you can do something like this:Basically the code passes to the function the names of the params the function will modify.
$GLOBALS
holds references to all defined variables in the global scope of the script. This means if the call is from another function it will not work:triggers notices undefined indexes
a
andb
. So another approach is to create an array with references to the variables the function will modify as:Note the
&
on theforeach
line. It is needed so not to create a new variable iterating over the array. PHP > 5 needed for this feature.您可以这样做,但它使用调用时传递引用,这在 PHP 5.3 中已弃用:
You can do it this way but it uses call-time pass by reference which is deprecated in PHP 5.3: