Skip to content

[Feature] Allow "write once" initialization of fields #4

Closed as not planned

Description

@lisachenko

Logic of typed properties requires initialization and engine allows to initialize such properties from everywhere, not only within constructor.

@nikic has suggested to follow this logic, eg. allow to initialize each property only once. Such implementation will allow to call private/protected setters with additional logic of initialization/validation.

Activity

  1. added
    enhancement
    on Feb 13, 2020
  2. lisachenko commented on Feb 13, 2020

    @lisachenko
    OwnerAuthor

    By Nikita:

    For example, people may wish to use newInstanceWithoutConstructor() + manual property initialization for custom serialization libs etc. Or even the same internally (unserialization, PDO fetch object, etc). These things are hard (impossible?) to make work if you introduce restrictions about constructors.

  3. unkind commented on Aug 24, 2020

    @unkind

    By the way, this is a common pattern for immutable objects

    public function withRed(int $red): self
    {
        assert($red >= 0 && $red <= 255);
        $color = clone $this;
        $color->red = $red;
        return $color;
    }

    Does this enhancement can may work it at least with

    public function withRed(int $red): self
    {
        assert($red >= 0 && $red <= 255);
        $color = clone $this;
        unset($color->red);
        $color->red = $red;
        return $color;
    }

    ?

    unset($this->foo); is legit way to make property uninitialized in new PHP versions, AFAIK.

  4. fefas commented on Sep 28, 2020

    @fefas

    I also have this case :)

  5. lisachenko commented on Sep 28, 2020

    @lisachenko
    OwnerAuthor

    I’m surprised that you have these cases 😃 Currently only ctor and static methods are allowed, sorry. But your comment was like small inspiration ))

    PS. Not sure, if I’ll be able to return to my projects soon. Very busy on my new work...

  6. fefas commented on Sep 29, 2020

    @fefas

    @lisachenko no problem, I would like to have more time as well. So, I could contribute to the package. I think what you did is a really good work.

    Just to explain a bit about my case: we need to keep the historical change log of an entity and there are many actions that have to be performed upon a version of the entity. The way we are doing it is by making the entity immutable and, everytime you need to update a field, we have this withSomethingMethod that basically clones the object, changes what is needed, and returns the new instance.

    We could of course use a contructor for it, but cloning and chaging makes the implementation a bit cleaner. I see your point of restricting mutability only within ctor and static methods and I actually agree with it, but I was wondering if there could be a solution that would be useful in our case.

  7. lisachenko commented on Nov 21, 2026

    @lisachenko
    OwnerAuthor

    Closing as not planned. PHP itself now covers everything this issue asked for, and #18 made this library a z-engine showcase rather than something to adopt for new code.

    • "Write once" initialization: readonly properties (PHP 8.1) can be initialized exactly once from inside the class, including from private setters that validate first.
    • withX() methods that clone and change one field: readonly properties can be re-initialized inside __clone() (PHP 8.3). PHP 8.5's clone with turns the wither into a one-liner:
    final readonly class Color
    {
        public function __construct(public int $red, public int $green, public int $blue) {}
    
        public function withRed(int $red): static
        {
            assert($red >= 0 && $red <= 255);
            return clone($this, ['red' => $red]);
        }
    }

    On PHP 8.5 and 8.6 this produces a new instance and leaves the original untouched. Writing $color->red = 1 from outside still throws "Cannot modify readonly property". Note that clone($obj, [...]) on readonly properties has to run inside the class's own scope (as above); called from outside it fails with a protected(set) error.

    Thanks @unkind and @fefas for the use cases. They're exactly the patterns the language ended up supporting natively.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions