How to create a new instance instead of pointing to the same instance when defining variable?

Asked

Viewed 22 times

0

When defining a variable of type Carbon i cannot copy the object (create new instance with the same properties), just point to the same instance, forcing me to create new objects manually.

Example:

$data_inicio  = Carbon::now()
                     ->hour(0)
                     ->minute(0)
                     ->second(0);

\var_dump($data_inicio); // retorna data 2019-07-19

$data_limite = $data_inicio;
$data_limite->addWeeks(8);
\var_dump($data_inicio); // retorna data 2019-09-13
\var_dump($data_limite); // retorna data 2019-09-13

There is a way to copy the instance instead of pointing to the same instance of the object, so that by changing the variable $data_limite i don’t change $data_inicio?

  • 1

    Just as $data_limite = clone $data_inicio?

1 answer

2


Use the reserved word clone.

$data_limite = clone $data_inicio;

Like the @Andersoncarloswoss said:

The clone will make the cloning shallow, that is, the internal references if keep intact. If the original instance depends on another instance, this second will be shared with the cloned instance, except if explicitly the class foresees this in the implementation of the method __clone.

The PHP documentation also mentions this:

[..] if its object holds a reference to another object which it uses and when replicating the parent object, it is desired that a new instance of that other object so that the replica has its own separate copy. [...]

  • 1

    The clone will make the cloning shallow, that is, the internal references will remain intact. If the original instance depends on another instance, this second instance will be shared with the cloned instance, except if explicitly the class predicts this in the method implementation __clone. I do not know if I understood right, but it seemed to me that you meant in the reply that even internal instances will be cloned.

  • I actually tried to explain what you explained clearly. I need to improve my answers and thank you for alerting :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.