The with*() methods in PSR-7 are documented to return a new instance,
not modify the existing instance. Yes, there's no way in PHP itself to
force that syntactically, which is why documentation exists. :-)
Also, in the benchmarks we've run the performance cost of all those new
objects is measured in nanoseconds, ie, small enough that we're not
worried about it. (Hats off to the PHP Internals folks for making that
fast!)
It is great that this is fast, but I wonder (maybe off-topic?) why do
it? I.e. it is clear that in something like:
$a = new Request->withHeaders(...)->withBody(...)
->withEncoding(...)->withETag(...)
the intermediate objects are useless and nobody needs 5 new objects when
you do it. Am I missing something here?
Hi,
my assumptions after some testing:
- This is only true in case of reassigning ($a = clone $a) the old variable, as refcount for underlying values remains 1 for all values in clones, so cow don't need to copy anything.
- If the old object is not thrown away, then memory consumption is doubled and the "fast" argument is wrong.
(Performance, of cloning an object without copying values and of some method calls, is negligible.)
Omit mutator methods (with*/set*) is a simple and logical way to achieve immutability in PHP. No need for const/final/...