PHP 8 propperty promotion

Tags:

Property promotion is new syntax in PHP 8 which allows property declaration in construct method. What we now is declare property in class then define same property which then assign value to declared property.

Before PHP 8

Consider below code which first defines property, same property is defined as parameter in construct method. This construct method then assign value of this parameter to property.

class User {
private string $name;

    public function __construct(string $name) {
        $this->name = $name;
    }
}
From PHP 8

Above class can shorten by using property promotion as show below:

class User {
    public function __construct(private string $name) {
    }
}

Now we don't even have to assign implicitly. When we create instance of class and pass parameter to constructor it gets assigned to property.

Standard property

We can define promoted property and standard property together.

class User {
    private int $age;

    public function __construct(private string $name, int $age) {
        $this->age = $age;
    }
}
Property type

Property type is not required we can declare property without its type, below code is valid.

class User {
    public function __construct(string $name) {
    }
}
Nullable type

Property with its data type and null value also called nullable is also allowed.

class User {

    public function __construct(private ?string $name, private ?int $age =  null) {
    }
}

But we can't do this:

class User {

    public function __construct(private string $name = null, private int $age =  null) {
    }
}
Duplication not allowed

If property is already defined in class, defining same in construct method is not allowed, see below code.

class User {
  private string $name;
    public function __construct(private string $name) {
    }
}
What's not allowed
  1. Property promotion is not allowed in abstract construct method and interface.
  2. Property type callable and var keyword also not allowed.
  3. Only constructor supports property promotion.