Viewed   114 times
$date1 = $date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

Now $date1 and $date2 contain the same date -- three years from now. I'd like to create two separate datetimes, one which is parsed from a string and one with three years added to it. Currently I've hacked it up like this:

$date2 =  new DateTime($date1->format(DateTime::ISO8601));

but that seems like a horrendous hack. Is there a "correct" way to deep copy a DateTime object?

 Answers

3
$date1 = new DateTime();
$date2 = new DateTime();
$date2->add(new DateInterval('P3Y'));

Update:

If you want to copy rather than reference an existing DT object, use clone, not =.

$a = clone $b;

Thursday, August 11, 2022
3

DateInterval is buggy on windows platform. See bug #51183. The official answer seems to be "use VC9 builds instead for now".

Monday, August 15, 2022
 
3

I use following wrapper class in my php5.2 apps: http://pastebin.ca/2051944. Untill php5.3 was released - it saves much my time

Thursday, November 3, 2022
 
4

You could use the Java Deep-Cloning Library to make deep copies of objects. It is really useful when you can't (or don't want) to make your classes serializable. The use is straight-forward:

Cloner cloner = new Cloner();

MyClass clone = cloner.deepClone(o);
// clone is a deep-clone of o
Sunday, September 18, 2022
 
lpirro
 
1

No. You don't have any way of accessing the garbage collector directly. As you say, the best you can do is make sure the object is no longer referenced.

IMO, it's better that way. The garbage collector is much smarter than you (and me) because years of research has gone into writing the thing, and even when you try and make optimisations, you're likely still not doing a better job than it would.

Of course if you're interfacing with a JS engine you will be able to control the execution and force garbage collection (among much more), although I very much doubt you're in that position. If you're interested, download and compile spider monkey (or v8, or whatever engine tickles your fancy), and in the repl I think its gc() for both.

That brings me to another point, since the standard doesn't define the internals of garbage collection, even if you manage to determine that invoking the gc at some point in your code is helpful, it's likely that that will not reap the same benefits across all platforms.

Monday, October 3, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :