On Wed, Jan 23, 2019 at 1:33 PM Andrey O Gromov <agro...@alfabank.ru> wrote:

> Full description
> https://wiki.php.net/rfc/code_free_constructor
> Draft realisation
> https://github.com/php/php-src/compare/master...rjhdby:constructor
>
> "Code free" constructor is constructor with only purpose to directly set
> object properties from received parameters and, optionally, call parent
> constructor.
>
> Main idea is to move such constructor declaration inside class
> declaration.
>
> Simple example:
>
> Current syntax
> class A extends B{
>     public $prop;
>
>     public function __construct($prop){
>         parent::__construct("BlaBla", $prop);
>         $this->prop = $prop;
>     }
> }
>
> Proposed syntax
> class A($prop) extends B("BlaBla", $prop) {
> }
>
> With respect, Andrey.


Two alternatives you might want to consider:

* https://wiki.php.net/rfc/automatic_property_initialization => Proposed
function public function __construct(int $this->x, int $this->y) {}, which
avoids the need for explicit property assignments in the ctor. However, the
property still needs to be declared separately.

* https://docs.hhvm.com/hack/other-features/constructor-parameter-promotion
=> Uses public function __construct(public int $x, public int $y) {} to
declare properties in-line in the constructor.

I think that *if* we want to add some kind of sugar of this type, then I'd
strongly prefer the syntax used by Hack than the one proposed here. It
makes a lot more sense to me intuitively, probably because the property
declarations still looks like normal property declarations, they just occur
in-line in the ctor.

Nikita

Reply via email to