How to use constructor promotion in PHP 8

Categorized as PHP

This is so good! The only thing that feels wrong is the empty brackets.

What is a constructor property promotion?

It is a new syntax that PHP 8 brings, allowing two simultaneous operations: Class property declaration and Constructor assignment, right from the constructor.

See how it works:

class Ugh {
    
  public $target;

  function __construct($target) {
    $this->target = $target;
  }

}

class Wew {

  function __construct(public $target) {}

}

See the official documentation.

Leave a reply

Your email address will not be published. Required fields are marked *