Advertisement
matthewpoer

PHP DateTime Object-Copying Correctly (Cloning)

Jul 12th, 2012
661
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.16 KB | None | 0 0
  1. $Monday = new DateTime();
  2. /* I have code here the succesfully finds the most recent Monday's date, and sets the DateTime object to that date */
  3. $DynamicDay = $Monday;
  4.  
  5. /*
  6.  * Setup the Array for this week, starting with Monday, going thru Saturday
  7.  */
  8. $week = array();
  9. $first = TRUE;
  10. for($i=0;$i<6;$i++){
  11.     if(!$first) $DynamicDay->modify("+1 Day");
  12.     $first = FALSE;
  13.     $week[$DynamicDay->format('l m-d-Y')] = array();
  14. }
  15. /*
  16. At this point, $DynamicDay holds a Saturday's date and $Monday *SHOULD* still be Monday, right?
  17. [Nope! [Chuck Testa]]
  18. http://us.php.net/manual/en/language.operators.assignment.php
  19. <blockquote>Note that the assignment copies the original variable to the new one (assignment by value), so changes to one will not affect the other. This may also have relevance if you need to copy something like a large array inside a tight loop.
  20.  
  21. An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.</blockquote>
  22.  
  23. So what's the proper solution?
  24. Instead of:
  25. $DynamicDay = $Monday
  26. Use:
  27. $DynamicDay = clone $Monday;
  28.  
  29. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement