Easy Wither Call

By Benoit Viguier

<?php

class Foo
{
    public function __construct(
        private readonly int $a,
        private readonly string $b,
    ) {
    }

    public function withA(int $a): self
    {
        return new self(...(get_defined_vars() + get_object_vars($this)));
    }

    public function withB(string $b): self
    {
        return new self(...(get_defined_vars() + get_object_vars($this)));
    }
}

$f = (new Foo(1, "foo"))
    ->withA(2)
    ->withB("bar");

var_dump($f);

Can be useful to create “with-ers” in an immutable (value) object with a LOT of readonly properties.

‘+’ is the addition of arrays, the first values have priority.

get_defined_vars() gets the local variables, with their name, unlike func_get_args().

Valid in PHP 8.1, with support for variadic and named keys.

See Also

PHP Features

Last updated: 14 July 2026