Andrea Faulds wrote on 17/11/2015 15:37:
Does it? You can write a five-line constructor which does what you need:
private function __construct(array $properties) {
foreach ($properties as $name => $value) {
$this->{$name} = $value;
}
}
You can do changes like so:
public function withName(string $name): self {
return new self(array_merge((array)$this, [
"name" => $name
]));
}
Not much code, no?
So, you need to reinvent "clone", in a less efficient, less readable,
way; restrict the form of your constructor, and the style of
implementation in your withName method; and for what gain exactly?
Implementations of this pattern using clone already exist, they are
efficient, clear, and maintainable; I'm not sure the promise of run-time
checking for mistakes would entice anyone to change them.
Would the modification be restricted to the lexical scope of the
constructor, or the dynamic scope? i.e. would this be allowed?
private function __construct($foo) {
$this->setFoo($foo);
}
If that's allowed, then you basically have a "freeze" action internally
anyway, that's called when the constructor returns; it's not a great
leap from there to having it exposed to userland to choose when it
happens. If that's not allowed, and the modifications have to be in the
constructor body itself, the value of the feature is further reduced.
That said, I'd be interested in examples of what any other languages do
around this area, and how it is used in practice.
Regards,
--
Rowan Collins
[IMSoP]
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php