Hi Michal,

thank you for this RFC. In combination with typed properties an object
initializer syntax becomes highly thought after in my opinion, especially
if you consider classes consisting mostly of typed PUBLIC properties, for
example data transfer objects or view models.

I find this especially important, because it helps with definitions that
otherwise create unitialized variables:

class Customer
{
     public DateTime $created;
}

$foo = new Customer();
// $foo->created now unitialized

Using the object initializer would leave the object in a fully consistent
state:

$foo = new Customer{ created=new DateTime('now') }

Two points I want to mention:

1. Currently with typed properties RFC its possible to declare a public
property as not nullable, but don't assign it. PHP will make it use the new
"unitialized" state. This is also done to allow unset() properties later to
allow hooks via __get. But with this new syntax, we could enforce that if a
class is new'ed with the object initialzer, then at end of the object
initializer + constructor, all properties are initialized, otherwise
Exception. This could help with bugs where you add a property to the class,
but forget to assign it in all cases where the class is new'ed +
intialized. One problem could be with RuntimeException that this only
crashes when the code is run, which is often too late, and would rather
warrant to just proceed and assume the developer knows what they are doing.
Also since object initialiizer only sets public properties, the check
should be for all public variables are initialized.

2.
You should add mention how the Reflection API changes. I would assume both
ReflectionClass and ReflectionObject get a new method
newInstanceFields(array $fields) with the following behavior:

$reflectionClass = new ReflectionClass(Customer::class);
$customer = $reflectionClass->newInstanceFields(['name' => 'Bert']);
// the same as
$customer = new Customer {name = 'Bert'};



On Thu, Sep 12, 2019 at 4:01 PM Michał Brzuchalski <
michal.brzuchal...@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
>
> I appreciate any feedback you all can provide.
>
> Thanks,
> --
> Michał Brzuchalski
> brzuc...@php.net
>

Reply via email to