PHP 中通过引用传递还是返回数组?

发布于 2025-01-03 08:25:24 字数 447 浏览 1 评论 0原文

我的所有函数都有多个参数并且需要返回多个值,我会像这样返回一个数组...

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我很坚强 2025-01-10 08:25:24

正如大多数评论所指出的那样,第一种方法(返回数组)更干净且更易于理解,因此按照该指标,它“更好”。

不过,根据您的用例,最好不要尝试返回多个值。考虑:

public function getDimensions() {
    return array(
        'width' => $this->_width,
        'height' => $this->_height
    );
}

$dim = $canvas->getDimensions();
echo $dim['width'], ' x ', $dim['height'];

比较:

public function getWidth() {
    return $this->_width;
}

public function getHeight() {
    return $this->_height;
}

echo $canvas->getWidth(), ' x ', $canvas->getHeight();

显然,这是一个人为的例子,但想象一下你的方法做了一些昂贵的事情而不是无聊的事情。现在想象一下,您只需要这组值中的第一个,但由于您的方法为每次调用计算所有值,因此您必须浪费地计算所有内容并丢弃不需要的内容。

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:

public function getDimensions() {
    return array(
        'width' => $this->_width,
        'height' => $this->_height
    );
}

$dim = $canvas->getDimensions();
echo $dim['width'], ' x ', $dim['height'];

Compared to:

public function getWidth() {
    return $this->_width;
}

public function getHeight() {
    return $this->_height;
}

echo $canvas->getWidth(), ' x ', $canvas->getHeight();

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文