PHP 中通过引用传递还是返回数组?
我的所有函数都有多个参数并且需要返回多个值,我会像这样返回一个数组...
function eg($a, $b) {
$a += 5;
$b += 10;
return array('a' => $a, 'b' => $b);
}
$no = eg(0, 5);
echo $no['a']; // 5
echo $no['b']; // 10
与通过引用传递相比,这被认为是不好的做法吗?
function eg(&$a, &$b) {
$a += 5;
$b += 10;
}
eg(0, 5);
echo $a; // 5
echo $b; // 10
这真的重要吗?使用上面的示例时,我什么时候想使用其中一种而不是另一种?性能上有什么区别吗?
谢谢
All of my functions that have multiple parameters and that need to return more than one of those values I return an array
like so...
function eg($a, $b) {
$a += 5;
$b += 10;
return array('a' => $a, 'b' => $b);
}
$no = eg(0, 5);
echo $no['a']; // 5
echo $no['b']; // 10
Is this considered bad practice compared to passing by reference ie;
function eg(&$a, &$b) {
$a += 5;
$b += 10;
}
eg(0, 5);
echo $a; // 5
echo $b; // 10
Does this really matter? When would I want to use one over the other when using the examples above? Is there any difference in performance?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如大多数评论所指出的那样,第一种方法(返回数组)更干净且更易于理解,因此按照该指标,它“更好”。
不过,根据您的用例,最好不要尝试返回多个值。考虑:
比较:
显然,这是一个人为的例子,但想象一下你的方法做了一些昂贵的事情而不是无聊的事情。现在想象一下,您只需要这组值中的第一个,但由于您的方法为每次调用计算所有值,因此您必须浪费地计算所有内容并丢弃不需要的内容。
As most of the comments have pointed out, the first method (returning an array) is cleaner and easier to understand, so by that metric, it's "better".
Depending on your use-case, though, it may even be better not to try and return multiple values at all. Consider:
Compared to:
This is a contrived example, obviously, but imagine that your methods do something expensive instead of frivolous. Now imagine that you only need the first of the set of values, but since your method calculates all of them for every invocation, you have to wastefully calculate everything and discard what you didn't need.