Re: [PHP-DEV] [RFC] Object Initializer

This is only part of a thread. view whole thread
  107137
September 16, 2019 06:22 michal.brzuchalski@gmail.com (=?UTF-8?Q?Micha=C5=82_Brzuchalski?=)
Hi Paul,

niedz., 15 wrz 2019 o 15:48 Paul M. Jones <pmjones@pmjones.io> napisał(a):

> > > > On Sep 12, 2019, at 09:00, Michał Brzuchalski < > michal.brzuchalski@gmail.com> wrote: > > > > Hi internals, > > > > I'd like to open discussion about RFC: Object Initializer. > > > > This proposal reduces boilerplate of object instantiation and properties > > initialization in case of classes without required constructor arguments > as > > a single expression with initializer block. > > > > https://wiki.php.net/rfc/object-initializer > > This reminds me of how Hack/HHVM would initialize object properties from > constructor parameters; I remember finding it very appealing. > > IIRC, you would provide the property signature as a constructor parameter > to trigger the initialization: > > ```php > class Foo > { > protected int $bar; > > public function __construct(protected int $bar) > { > } > > public function getBar() : int > { > return $this->bar; > } > } > > $foo = new Foo(1); > echo $foo->getBar(); // 1 > ``` > > Perhaps something like that is worth adopting here. >
What you're describing AFAIR was called "constructor argument promotion" and this is not kind of problem current RFC tries to solve. Argument promotion looks useful for constructors, in the name of good practice constructors and methods|functions in general should not require a lot of arguments. Thank you for your feedback but I believe the suggested solution is off-topic. Thanks, Michał Brzuchalski
  107142
September 16, 2019 07:41 arnold.adaniels.nl@gmail.com (Arnold Daniels)
Features like `func_get_args(ARGS_OBJECT)` and `hoist` aren't really needed. You can use `get_defined_vars()` instead.

Many of my classes have constructors like;

public function __construct(int $foo, string $bar, bool $flag = false)
{
set_object_vars($this, get_defined_vars());

}

FYI `set_object_vars` is a user-space function that does the reverse of `get_object_vars`. You could use a `foreach` loop instead.
----

However when a class for a data object has 20 properties, I don't really want to put all 20 as constructor arguments. The object initialize RFC be the preferred solution for me in that case, even if named parameters was also supported. As such, I don't think the two features are mutually exclusive.

[Arnold Daniels - Chat @ Spike](https://www.spikenow.com/?ref=spike-organic-signature&_ts=5w9qi)	[5w9qi]

On September 16, 2019 at 6:22 GMT, Michał Brzuchalski brzuchalski@gmail.com> wrote: