duanbanfei2875 2018-06-07 03:53
浏览 20
已采纳

PHP对象数组要求我克隆每个对象,否则它将持续更改

I have a class that has an array of objects. I have a function that loops over the array, and formats a value, and then just puts these formatted values into a separate array... and then returns them.

Here is relevant code:

class MoneyThing {
    public $taxes = array();

    public function formatTaxes(){
        // Pretend the $taxes array is populated as such when called, with a single LeviedTax object
        //  Array
        //  (
        //      [0] => LeviedTax Object
        //      (
        //          [name] => HST
        //          [rate] => 13
        //          [total] => 17.55
        //          [harmonized] => 1
        //      )
        //  )

        echo "<pre>".print_r($this->taxes, true)."</pre>";

        $formattedTaxes = $this->taxes;

        foreach($formattedTaxes as $tax){
            // Make a clone of the object.  PHP object are copied to other vars by reference by default.
            // $tax = clone $tax;

            // Just adds a dollar sign
            $tax->total = money_format($tax->total);
            $formattedTaxes[] = $tax;
        }

        echo "<pre>".print_r($this->taxes, true)."</pre>";

        // Will print the 'total' with a dollar sign. Why???:
        //  Array
        //  (
        //      [0] => LeviedTax Object
        //      (
        //          [name] => HST
        //          [rate] => 13
        //          [total] => $17.55
        //          [harmonized] => 1
        //      )
        //  )

        return $formattedTaxes;
    }
}

I have printed the class's array before and after the foreach loop. I am seeing the array keep these changes, as if I made them directly by reference within the foreach. I am expecting to have the same array before and after the loop as I'm not even working with said array.

It is my understanding that Arrays are copied plain and simple, whereas Objects are copied by reference. However, since I am copying an array of objects I would expect to not have to use clone because it's not by reference... right?

How come I have to uncomment $tax = clone $tax; in order to not actually persist the formatted values?

  • 写回答

1条回答 默认 最新

  • doukong9982 2018-06-07 04:15
    关注

    Objects are always passed by reference. Technically speaking array of objects in PHP is array of references to objects.

    From design perspective you are trying to solve the wrong problem.

    Fairly speaking you don't need this method. The calls like money_format() should be implemented at the moment of tax output, for example when you will interpolate this into HTML or write into CSV.

    If you are really need to output this stuff multiple time, for example you have to print the formatted tax value into dozens different file formats, it is worth to introduce little overhead in the form of formattedTotal property on the LeviedTax class. In this case you will have a setter like

    class LeviedTax {
      public function setTotal($total) {
        $this->total = $total;
        $this->formattedTotal = money_format($total);
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 poi合并多个word成一个新word,原word中横版没了.
  • ¥15 【火车头采集器】搜狐娱乐这种列表页网址,怎么采集?
  • ¥15 求MCSCANX 帮助
  • ¥15 机器学习训练相关模型
  • ¥15 Todesk 远程写代码 anaconda jupyter python3
  • ¥15 我的R语言提示去除连锁不平衡时clump_data报错,图片以下所示,卡了好几天了,苦恼不知道如何解决,有人帮我看看怎么解决吗?
  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?