When working with immutable objects, modifying a single property requires cloning the object and then altering the clone inside a custom method or constructor. PHP 8.5 introduces the 'clone with' construct, allowing you to create a modified copy of an object while updating specific properties in a single, concise expression.

PHP 8.5 Example:

PHP
readonly class Point
{
    public function __construct(public int $x, public int $y) {}
}

$original = new Point(10, 20);

// Create a copy with an updated 'x' value
$modified = clone $original with { x: 50 };

echo $modified->x; // Outputs: 50
echo $modified->y; // Outputs: 20

The articles and images featured on this platform were generated with the assistance of AI tools.