On 17/11/2015 13:26, Lester Caine wrote:
On 17/11/15 11:04, Rowan Collins wrote:
If you look at the PSR-7 implementation I linked to earlier [1], there's
no such boilerplate, just a single call to "clone $this", and PHP does
it all for you. But that doesn't work with a simplistic definition of
immutable like "mutable in constructor" or "mutable until non-null"; you
need to be able to "freeze" an instance once you've set it up, or have
privileged (private) methods which are allowed to mutate the properties.
Indeed, maybe there is a use for a new language construct to help reduce the boilerplate, but it could be done afterward, the "everything in the constructor" works fine. If there is too much in the construct it might be a sign that the class is doing too much and should be refactored in smaller classes

slightly off topic, in rust you initialize struct like that :

MyStruct {
  myprop1: myvalue1,
  myprop2: myvalue2,
}

It could be extended in php to have something like that :

class MyClass {
  private $myProp1;
  private $myProp2;

  static create function ($prop1) {
    return new self {
      myProp1: $prop1;
      myProp2: 'initialValue'
    };
  }

  public function withProp2($prop2) {
    return new self {
      myProp2: $prop2,
*: $this, // here * would mean: properties other than myProp2 are taken from $this
    };
    // or like that
    return self {
      myProp2: $prop2,
      ... $this, // properties other than myProp2 are taken from $this
    };
  }
}

note: I'd like this kind of construct even without the immutable stuff (would avoid having to write boilerplate __construct)
read_only=true; ... after the value is set.

Switch off all the 'setter' magic once the object has been created, but
I still see a problem where this only really works with simple values?
If I've created a more complex object, while it's 'value' may need to be
fixed, how it's displayed may involve setting alternative defaults, so
one still needs to be able to set other variables in the object.
In that case if you don't want to make its "display settings" immutable you should have 2 classes, one with the immutable 'value' and another containing the 'value' and the "display settings"



--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to