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?