Visibility and Constructors
Constructor Promotion
Constructor property promotion creates and initializes a property in one place.
Constructor Promotion
constructor_promotion.php
<?php
class Course
{
public function __construct(private string $title, private int $lessons)
{
}
public function summary(): string
{
return $this->title . ":" . $this->lessons;
}
}
$lessons = ;
$summary = (new Course("PHP", $lessons))->summary();
echo "lessons=" . $lessons . "\n";
echo "summary=" . $summary . "\n";
<?php
class Course
{
public function __construct(private string $title, private int $lessons)
{
}
public function summary(): string
{
return $this->title . ":" . $this->lessons;
}
}
$lessons = ;
$summary = (new Course("PHP", $lessons))->summary();
echo "lessons=" . $lessons . "\n";
echo "summary=" . $summary . "\n";
<?php
class Course
{
public function __construct(private string $title, private int $lessons)
{
}
public function summary(): string
{
return $this->title . ":" . $this->lessons;
}
}
$lessons = ;
$summary = (new Course("PHP", $lessons))->summary();
echo "lessons=" . $lessons . "\n";
echo "summary=" . $summary . "\n";
compact initialization
Promoted constructor properties reduce repeated boilerplate for simple value objects.