Dirk J. Faber
Dirk J. Faber

Reputation: 4701

PHP adding days to a date in a new variable changes the other

I have a variable invoiceDate, which is a datetime type. I calculate the dueDate by adding 14 days to the invoiceDate with the following:

private $invoiceDate; // this is any datetime. 
private $dueDate;

public function calculateDueDate(){
    $due = date_add($this->invoiceDate, new \DateInterval('P14D'))  ;
    return $due;
}

public function getInvoiceDate()
{
    return $this->invoiceDate;
}

public function getDueDate()
{
    $this->dueDate = $this->calculateDueDate();
    return $this->dueDate;
}

What I don't get is that when I use the method getDueDate() or getInvoiceDate() I always get the original invoiceDate plus 14 days, on both methods. Why is the original date affected and what can I do to prevent this?

Upvotes: 0

Views: 64

Answers (1)

u_mulder
u_mulder

Reputation: 54831

Open date_add manual and see that first argument of date_add is:

A DateTime object returned by date_create(). The function modifies this object.

So, you need to modify another object, for example, a clone:

public function calculateDueDate(){
    $due = date_add(
        clone $this->invoiceDate, 
        new \DateInterval('P14D')
    );
    return $due;
}

Upvotes: 4

Related Questions