0

My question is $b the same as $a in the output? Am I just passing a reference to $a when using ($b = $a) and not making a copy of the object?

$a = new DateTime('2014-01-15');
$i = new DateInterval('P1D');
print $a->format('Y-m-d') . PHP_EOL;          // 2014-01-15
$b = $a;
print $a->add($i)->format('Y-m-d') . PHP_EOL; // 2014-01-16
print $b->format('Y-m-d') . PHP_EOL;          // 2014-01-16
c3cris
  • 1,276
  • 2
  • 15
  • 37

1 Answers1

2

Note the use of clone:

$a = new DateTime('2014-01-15');
$i = new DateInterval('P1D');
print $a->format('Y-m-d') . PHP_EOL;          // 2014-01-15
$b = clone $a;                                // Here we clone the object
print $a->add($i)->format('Y-m-d') . PHP_EOL; // 2014-01-16
print $b->format('Y-m-d') . PHP_EOL;          // 2014-01-15

Further explanation from the docs: if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy. It sounds like just setting $a = $b will have the same initialization of the object, meaning if one changes the other does. The variable $b becomes a sort of symbolic link to the initialized object held in $a.

Sam
  • 20,096
  • 2
  • 45
  • 71
  • I see, can you explain then what a simple $b = $a does then? – c3cris Jan 15 '14 at 18:16
  • 1
    http://stackoverflow.com/questions/11184743/difference-between-a-b-a-b-and-a-clone-b-in-php-oop Found a good explanation ! I will accept your answer asap. TY – c3cris Jan 15 '14 at 18:22