MENU
Constructor Property Promotion
Before PHP 8.0, giving a class a typed property meant declaring the property, then repeating its name and type in the constructor just to copy the argument across. Here is the long-hand version.<?php
class Point {
public float $x;
public float $y;
public function __construct(float $x, float $y) {
$this->x = $x;
$this->y = $y;
}
}
$p = new Point(1.5, 2.5);
echo "{$p->x}, {$p->y}\n";
?>1.5, 2.5
<?php
class Point {
public function __construct(
public float $x,
public float $y
) {
}
}
$p = new Point(1.5, 2.5);
echo "{$p->x}, {$p->y}\n";
?>1.5, 2.5
<?php
class User {
public string $slug; // an ordinary, non-promoted property
public function __construct(
public string $name, // promoted
private int $age, // promoted
string $prefix = 'user' // ordinary parameter, not a property
) {
$this->slug = strtolower($prefix . '-' . str_replace(' ', '-', $name));
}
public function getAge(): int {
return $this->age;
}
}
$u = new User('Jane Doe', 30);
echo $u->name, "\n";
echo $u->slug, "\n";
echo $u->getAge(), "\n";
?>Jane Doe
user-jane-doe
30
<?php
class Base {
public function __construct(final public string $id) {
}
}
class Child extends Base {
// no attempt to redeclare $id here
}
$c = new Child('abc-1');
echo $c->id, "\n";
?>abc-1