Quick DTO Or VO Copy

By Benoit Viguier

<?php

class DTO {
    public function __construct(
        public int $a,
        public int $b,
        public int $c,
        public int $d,
        public int $e,
        public int $f,
    ) {}
}

$dto = new DTO(1, 2, 3, 4, 5, 6);
var_dump($dto);

// #PHP 8.2+, with named parameters in arrays
$copy = new DTO(...(['d' => 42] + get_object_vars($dto)));
var_dump($copy);

// #PHP 8.0–1+, with unnamed parameters in arrays
$copy2 = new
DTO(...array_values(array_merge(get_object_vars($dto), ['d' => 42])));
var_dump($copy2);

// #PHP 7.4– : not supported

A small PHP trick, combining named parameters, spread and union arrays operators to easily create a modified copy of a DTO: https://3v4l.org/ZWX5G#v8.2.10

It’s fun if you have a lot of parameters, but using a string containing the parameter’s name isn’t really satisfactory

It is possible to extend this syntax to PHP 8.0+ with a clever array_values() / array_merge(): https://3v4l.org/igrsW

$copy = new DTO(...(array_values(array_merge(get_object_vars($dto), ['d' => 43]))));

Now, this extended syntax is an easy prey to property definition order, constructor argument order, and temporary property deletion, unlike your original approach.

See Also

PHP Features

Last updated: 14 July 2026