Re: Immutable modifier

From: Date: Tue, 17 Nov 2015 15:37:21 +0000
Subject: Re: Immutable modifier
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-89268@lists.php.net to get a copy of this message
Hi, Rowan Collins wrote:
Hi Andrea, Andrea Faulds wrote on 17/11/2015 01:47:
Larry Garfield wrote:
The "everything in the constructor" is the problem. That results in, essentially, an obscenely long function call that just happens to be named __construct(). If I wanted something that obscure and hard to work with I'd just use anonymous arrays. :-)
Huh? "with" methods and __construct are not exclusive. In fact, you could have a private constructor and only have "with" methods. Only allowing assignment to properties in the constructor doesn't prevent having a nice API: have your methods call the constructor. I don't see what you're getting at here.
Making the "with" methods wrap the constructor tidies the public API, but that (private) constructor needs to be just as complex as Larry said earlier - you've got to manually extract all the properties of one instance, and pass them as parameters to the other. Or, you could copy them one by one inside the body of the constructor, which comes to the same thing - lots of boilerplate.
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? Thanks. -- Andrea Faulds http://ajf.me/

« previous php.internals (#89268) next »