Member since
i think it went too far with the virtuals
<?php class User { public string $name = 'default' { set { if (strlen($value) === 0) { throw new ValueError("Name must be non-empty"); } $field = ucfirst($value); } get { notifyMutationObserver(); return $this->name; } } public string $badIdeaNoSetterVirdualProp { get { return $this->name; } // set ERROR! I don't like this idea... } public readonly array $lazy { get { return $this->lazy = getBigData(); } // set NO! see declaration, its readonly } public function __construct(string $name) { $this->name = $name; unset($this->lazy); } } $u = new User('roman'); var_dump($u->name);
There are some arguments against the implementation and I agree to those. But in addition I don't agree to the concept itself, personally, because I am convinced that immutability is key when enforcing domain logic. E.g. the example above could be replaced by:
readonly class User { public function __construct(public string $name) { if (strlen($name) === 0) { throw new ValueError('Name must be non-empty'); } } public function withName(string $newName): self { return new self($newName); } }
Or, even better IMO, with value objects that validate themselves:
readonly class User { public function __construct(public Name $name) {} public function withName(Name $newName): self { return new self($newName); } } readonly class Name { public function __construct(public string $value) { if (strlen($value) === 0) { throw new ValueError('Name must be non-empty'); } } }
Granted, this is only one example and immutabilty is not a silver-bullet. But I haven't come across a usecase for property hooks that was really convincing yet
Moving to C# is not a good way IMHO. We will end with classes where properties are heavily mixed with the logic before actually we see class methods.
Getters and setters work just fine.
Additionally RFC says there is a large and obscure performance penalty for array
typed properties and it's introduces additional complexity.