Combine property declarations and constructor parameter assignments in PHP 8 for concise class definitions.
Declaring class properties, parameter signatures, and manual $this->prop = $prop assignments creates boilerplate code. Constructor property promotion combines all three steps in the parameter list.
namespace App\Services;
class PaymentProcessor
{
// Property promotion combines declaration, type, and assignment
public function __construct(
public readonly StripeClient $client,
private string $apiKey,
protected int $timeout = 30,
) {}
}
- Eliminates repetitive property definitions and assignment statements
- Supports visibility modifiers (public, protected, private) and readonly flags
- Fully compatible with docblocks, attributes, and default values
Related Tips
View all tips →
PHP
Syntax
Match Multiple Values in a Single Match Arm in PHP
Separate multiple comma-delimited values within a single match expression arm to group identical execution branches.
READ
>
PHP
Syntax
Unpack Arrays with Spread Syntax in PHP 8.1
Use array unpacking (...) inside square bracket array literals for string-keyed and indexed array merging.
READ
>