On Mon, May 15, 2023, at 8:32 AM, Lynn wrote:

> It's starting to get crowded in object constructors. The following example
> is so much more readable and maintainable imo. Would it be possible to
> still add the quick assignment as a language feature? I'm personally not
> happy having property definitions in both the class body _and_ the
> constructor signature.
>
> ```php
> class User {
>     private string $first;
>     private string $last;
>     public string $fullName {
>         get => $this->first . ' ' . $this->last;
>         set => [$this->first, $this->last] = explode(' ', $value, 2);
>     }
>
>     public function __construct($this->fullName) {}
> }
>
> // vs
>
> class User {
>     private string $first;
>     private string $last;
>
>     public function __construct(
>         public string $fullName {
>             get => $this->first . ' ' . $this->last;
>             set => [$this->first, $this->last] = explode(' ', $value, 2);
>         }
>     ) {}
> }
>
> // or
>
> class User {
>     private string $first;
>     private string $last;
>     public string $fullName {
>         get => $this->first . ' ' . $this->last;
>         set => [$this->first, $this->last] = explode(' ', $value, 2);
>     }
>
>     public function __construct(string $fullName)
>     {
>         $this->fullName = $fullName;
>     }
> }

The last version skips constructor promotion entirely, so will absolutely work. 
 For this case, that's frankly the best approach, since you're right, the 
constructor gets rather messy otherwise.

Changing the syntax and semantics for CPP itself (as in the first code block 
above) is considerably out of scope for this RFC.  I recall someone pointing 
out why double-declaring the property would cause problems, but I forget the 
reason.  In any case, another promotion syntax would be a topic for another 
RFC.  I don't recall off hand the reasons Nikita had for choosing the syntax 
that ended up being used.

--Larry Garfield

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

Reply via email to