In PHP, how do I concatenate objects with PHP 8+ features?

In PHP 8 and later, you can use the various features to construct and concatenate objects easily.

keywords: PHP 8, object concatenation, PHP features
description: Learn how to concatenate objects in PHP 8 using new features effectively.
<?php class Person { public $name; public $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } class ConcatenatedPerson { public function __construct(private Person $person1, private Person $person2) {} public function concatenate(): string { return "{$this->person1->name} is {$this->person1->age} years old, " . "{$this->person2->name} is {$this->person2->age} years old."; } } $john = new Person('John', 30); $jane = new Person('Jane', 25); $combined = new ConcatenatedPerson($john, $jane); echo $combined->concatenate(); // Output: John is 30 years old, Jane is 25 years old. ?>

keywords: PHP 8 object concatenation PHP features