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 😕

ZWX5G - created on 3v4l.org

View the output of this script on 3v4l.org: the online PHP shell with 250+ PHP versions

@b_viguier would also work nicely with value objects, not just DTOs
@dgoosens Ho yes, you’re right!
TBH this is what I had in mind, but I often mix both terms 😅

@b_viguier You can extend this syntax to #PHP 8.0+ with a clever array_values() / array_merge() in that syntax.

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.

#phptip #phptrick

igrsW - created on 3v4l.org

View the output of this script on 3v4l.org: the online PHP shell with 250+ PHP versions

@dseguy @b_viguier I am really interesting in which case this is useful :)