Patch: Marking DateTime Instances Immutable

From: Date: Sun, 05 Dec 2010 00:11:37 +0000
Subject: Patch: Marking DateTime Instances Immutable
Groups: php.internals 
Request: Send a blank email to internals+get-50844@lists.php.net to get a copy of this message
In the current implementation DateTime is not a value object, but its internal state can be modified at any given time. This can lead to very obscure bugs when references to DateTime objects are shared or objects are passed through a chain of methods/functions that modify it. Using DateTime is not side-effect free. I propose to allow to work with DateTime objects that are marked as immutable optionally. This means that all methods add, sub, modify, setDate, setTime, setISODate, setTimestamp and setTimezone will return a NEW instance of Datetime instead of reusing the old one. I also talked to Derick about this and he agrees that immutable DateTime objects would be desirable. I have talked to many other people who agreed that the current behavior is weird. My proposed syntax would be: $immutableDateTime = date_create("2010-12-05", null, true); $immutableDateTime = new DateTime("2010-12-05", null, true); $immutableDateTime = DateTime::createFromFormat("%Y-%m-%d", "2010-12-05", null, true); Where the third and fourth variable respectivly are boolean flags $immutable yes or no. Also the DatePeriod iterator would be modified. If an immutable start date is passed the date iterator would also create immutable dates. I have attached a patch that implements this functionality and a little test-script that shows how it would work. This is the first complex bit of C-code that I did so please bear with any mistakes I made ;-) Also i havent followed the coding standards. Any feedback is greatly appreciated. My C-Skills arent that good so i am not finished with an additional solution allowing to call a method "setImmutable()" on any datetime instance, marking it as immutable. Obviously this would only mark the instance as immutable, allowing to accept a flag to reset it to be mutable would be counter-productive. The only drawback I see to this patch is the additional int variable on the _php_date_obj and _php_date_period structs. I am not sure if they affect memory in such a way that this solution isn't viable. If this topic needs more discussion or pro/cons I am willing to open up an RFC for a more detailed discussion.

Attachment: [text/x-php] datetime.php
Attachment: [text/x-diff] php_immuntable_datetime.patch
« previous php.internals (#50844) next »