dongrou839975 2012-02-08 18:13
浏览 19

通过引用传递或返回PHP中的数组? [关闭]

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

  • 写回答

1条回答 默认 最新

  • doujiurong7210 2012-02-08 18:48
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算