如何在php中通过引用传递无限参数
我有一个 php 函数,它有无限数量的参数,我从 func_get_args() 获得这些参数。我有一些带有参数的操作(更改字符串或执行某些操作),我希望这就像通过引用传递参数一样。是否可以?
例子:
$test = 'foo';
$test2 = 'bar';
function test(){
$args = func_get_args();
foreach($args as $arg)
$arg .= 'baz';
}
test($test, $test2);
I have php function that has an unlimited number of args which I am getting from func_get_args(). I have some operations with arguments (changing string or doing something) and I want this to be like a passing argument by reference. is it possible?
example:
$test = 'foo';
$test2 = 'bar';
function test(){
$args = func_get_args();
foreach($args as $arg)
$arg .= 'baz';
}
test($test, $test2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
从 PHP-5.6 开始,您可以使用 可变参数 引用:
Since PHP-5.6 you can use a variadic reference:
正如PHP:按引用可变长度参数列表?中的回答, PHP 中无法组合可变长度并通过引用传递函数参数。相反,链接的答案使用了声明 100 个
&argx
的技巧,然后使用get_num_args()
来计算实际使用了多少个。恭喜,您发现了 PHP 中的一个特别困难的角落;)它还展示了如何使用 PHP 5.6+ 变量来做到这一点。
As answered in PHP: variable-length argument list by reference?, there is no way in PHP to combine variable-length and pass by reference function arguments. Instead, the linked answer uses a hack of declaring 100
&argx
s, then usingget_num_args()
to figure out how many were actually used. Congratulations, you found a particularly hard corner in PHP ;)It also shows how to do it with PHP 5.6+ variadics.
我非常怀疑这是可能的,但我确实知道一种方法可以得到你想要的东西:
I highly doubt that's possible, but I do know one way you could get what you want:
这是可行的:
但是,这使用了已弃用的调用时传递引用。
This works:
However, this uses call-time pass by reference which is deprecated.
当我做类似下面的例子的事情时,效果很好。我认为关键是在foreach中设置引用。
Works fine for me when doing something like the example below. I think the key is setting the reference in the foreach.
我也需要这个功能,我想出了一个解决方案。
但这取决于 php >= 5.4。如果您使用的是 <= 5.4,请使用 array() 语法而不是 []。
我喜欢[] 不过,更好了:)
I needed this functionality as well, I came up with a solution.
This depends on php >= 5.4 though. If you're on <= 5.4, use array() syntax instead of [].
I love [] tho, much better :)
使用对象是解决方案
Using objects is the solution