Pages

Wednesday, March 26, 2014

Constructor Argument Promotion

Constructor Argument Promotion 

Most PHP programmers are familiar with defining class properties.
<?hh
class Person {
  private 
string $name;
  private 
int $age;

  public function 
__construct(string $nameint $age) {
    
$this->name $name;
    
$this->age $age;
  }
}
This is pretty straightforward. Declare the property. Assign the property with a value passed to the constructor.
With just a few properties, this is not too cumbersome. Imagine a class with ten properties. It could easily become tedious to basically declare the properties twice, once in the class header and once in the constructor.
Introducing constructor argument promotion. This is a small, yet very useful syntatic improvement provided by the Hack language. Now instead of writing code like the example above, you can write:
<?hhclass Person {
  public function 
__construct(private string $name, private int $age) {}
}
That's it. One line. The class members will automatically be created and assigned to what is passed into the constructor. Syntatic sugar, yes. Typing and productivity win, for sure.



No comments:

Post a Comment