Hi Stas, > On 1 Feb 2015, at 00:55, Stanislav Malyshev <smalys...@gmail.com> wrote: > > >> 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?
I assume the reason for doing this is so you can’t ever modify the object from a distance, you must always create a new one to avoid messing up anything with an existing handle on it. As you mention, though, this means that you get useless intermediate objects. This use case could be solved much better if we had copy-on-write/value-type classes like PHP 4 had. If Request was a value-type class, then you could do this: $a = new Request(); $a->addHeaders(…); $a->setBody(…); $a->setEncoding(…); $a->setETag(…); Here, there’s no redundant objects made, but if you pass $a on, it’d be automatically copied by PHP, so you don’t need to worry about it being modified. Would that make sense? It’s no different than how our existing value types like scalars and arrays work. -- Andrea Faulds http://ajf.me/ -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php