I'm having the same poblem about making a copy of an object without reference in PHP but that soluction is not working.
I want to take all elements of a collection, change one property (add months) and push that new element into a new collection.
So I've used clone
in order to get a totally new instance of an Invoice
wich should be affected just that instance, but is not.
With this code:
while($thisInvoiceYear <= CURRENT_YEAR) {
$clonedInvoice = clone($thisInvoice);
$this->extendedInvoices->push($clonedInvoice);
$toSaveInvoice = $this->extendedInvoices->last();
$thisInvoiceYear = $this->getCurrentYear($toSaveInvoice);
$toSaveInvoice->Schedule->StartDate = Carbon::parse($toSaveInvoice->Schedule->StartDate)->addMonths($period);
unset($clonedInvoice);
}
Where $thisInvoice
is an object of the Invoice collection, $this->extendedInvoices
is a method of the class Invoice.
The problem is that every change done in $toSaveInvoice
also affects to the original collection element. After 3 iterations, date is the same for all elements of extendedInvoices and should not be:
I am using Laravel 5.2, but I think there aren't helpers to clone an element of a collection.
Do you know why clone()
is not working? Thanks a lot for your help.