rfc:object-initializer

This is an old revision of the document!


PHP RFC: Object Initializer

Introduction

PHP doesn't have a convenient literal syntax for creating an object and initializing properties. This makes creating objects and initializing its state quite laborious. Every time you have to:

  1. Instantiate an object.
  2. Assign each needed accessible properties with the value.
  3. Pass created a fully initialized object.

That's where object initializer optimization can benefit with single expression statement and it can be used to initialize any kind of object (including anonymous classes). The initializer block can use any properties and variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.

Proposal

Object initializers allow to assign values to any accessible properties of an object at creation time without having to invoke a constructor followed by lines of assignment statements. The object initializer syntax enables to specify arguments for a constructor or omit the arguments (and parentheses syntax).

The following example shows how to use an object initializer with a named type, Car and how to invoke the parameterless constructor.

<?php
 
class Customer
{
  public $id;
  public $name;
}
 
$customer = new Customer {
  id = 123,
  name = "John Doe",
};
 
class Car
{
  public int $yearOfProduction;
  public string $vin;
}
 
$car = new Car {
  yearOfProduction = 2019,
  vin = "1FTFW1CVXAFD54385",
};

The object initializers syntax allows to create an instance, and after that, it assigns the newly created object, with its assigned properties, to the variable in the assignment.

Above example is an equivalent to the previous one.

<?php
 
$customer = new Customer();
$customer->id = 123;
$customer->name = "John Doe";
 
$car = new Car();
$car->yearOfProduction = 2019;
$car->vin = "1FTFW1CVXAFD54385";

The main difference is that object initializers allow creating a new object, with its assigned properties in a single expression. For eg. factory methods where normally a significant amount of argument has default values or simple Data Transfer Objects could benefit.

Lexical scope

Initializer block uses current lexical scope, which means all local variables, accessible properties and methods, global variables and functions are possible to use for initializing object properties inside the object initializer block.

Visibility

Initializer block allows assigning values to properties accessible from the current class context. This means if used to initialize object properties from inside the same class like for eg. using named static constructor all standard visibility rules apply as it is just a simplification of object creation and assigning values statements.

Above example shows the correct behaviour of visibility rules.

<?php
 
class Customer
{
  private string $name = '';
  protected ?string $email = null;
 
  public static function create(string $name, ?string $email = null): self
  {
    return new self {
      name = $name, // assign private property within the same class
      email = $email, // assign protected property within the same class
    };
  }
}
$customer = Customer::create("John Doe", "john.doe@example.com");

Magic methods

An object initializer is just a simplification of instantiating an object and initializing property values that's why all rules regarding properties apply.

Using an object initializer combined with magic set method call might be used if an additional validation is required.

<?php
 
class EmailAddress
{
  private string $email;
  public ?string $name = null;
 
  public function __set(string $name, $value): void
  {
    if ($name !== "email") {
      return;
    }
    if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
      throw new InvalidArgumentException("Invalid email address");
    }
    $this->email = $value;
  }
}
 
$email = new EmailAddress {
  email = "john.doe@example.org",
  name = "John Doe",
};

Anonymous classes

Initializer block stands instead of constructor arguments which means in case of anonymous classes that place is right before the class definition.

Above example shows how to use object initializer with anonymous classes.

<?php
 
$email = new class {
  email = "john.doe@example.org",
  name = "John Doe",
  birthDate = new DateTime('1970-01-01'),
} {
  public DateTime $birthDate;
};

Undeclared properties

As stated before all property rules apply inside initializer block, which means properties can be set even if they're not declared then initializer block creates dynamic properties and assign their value.

Dynamic properties can be set by their name or by a variable which holds the name of property.

Above example shows how to use object initializer with dynamic properties.

<?php
 
$baz = "baz";
$obj = new stdClass {
  foo = "bar",
  $baz = true,
};

Backward Incompatible Changes

None.

Proposed PHP Version(s)

Targets next PHP 8.x. Which is PHP 8.0

RFC Impact

To SAPIs

None.

To Existing Extensions

None.

To Opcache

Would require opcache changes.

New Constants

None.

Open Issues

Calling ctor before or after initializer or using a ctor at all is not resolved yet. Calling zero args ctor might be an option.

Future Scope

Presume default stdClass

In a future removal of a class name before initializer block could be considered as a simplification for creating new instances of stdClass with initializer block to keep it in a single expression.

<?php
 
echo json_encode(new stdClass { foo = "bar" }); // will output {"foo":"bar"}
echo json_encode(new { foo = "bar" }); // could be equivalent

Splat operator

In a future splat operator could be used to expand array with string keys as arguments with the key parameter names.

<?php
 
$data = [
  "email" => "john.doe@example.org",
  "name" => "John Doe",
];
$customer = new Customer { ...$data };

Proposed Voting Choices

As this is a language change, a 2/3 majority is required.

The vote is a straight Yes/No vote for accepting the RFC and merging the patch.

Patches and Tests

Not implemented.

A volunteer to help with implementation would be desirable.

Implementation

Not implemented.

References

rfc/object-initializer.1567678930.txt.gz · Last modified: 2019/09/05 10:22 by brzuchal