php version guide

PHP 8.5 `clone()` With Changed Properties

PHP 8.5 turns cloning into a function form that can reassign selected properties while copying an object. This is especially useful for readonly value objects that need a clear “with changed value” operation.

Changes Worth Recognising

  • Use clone($object, ["property" => $value]) to create a modified copy.
  • The original object is not mutated.
  • Keep property names reviewable and cover copy operations with tests.
  • Value-object copying does not make referenced objects deeply immutable.

Copy a Readonly Value

PHP example
<?php

readonly class Page
{
    public function __construct(
        public string $title,
        public bool $published,
    ) {}

    public function publish(): self
    {
        return clone($this, ['published' => true]);
    }
}

$draft = new Page('PHP 8.5', false);
$published = $draft->publish();

echo $draft->published ? "live\n" : "draft\n";
echo $published->published ? "live\n" : "draft\n";

// Prints:
// draft
// live

Upgrade Review

  • Perform readonly property changes from a scope allowed to write those properties.
  • Test that the original remains unchanged.
  • Review nested object references when deep independence matters.
  • Use a named method when the domain transition needs validation or side effects.

Use this syntax inside a value-object method for simple copy-with changes; retain domain methods for transitions with business rules.

Practice

Publish a Copied Value Object

Create a readonly value object with a boolean status. Add a method that returns a copy with the status changed, then print both the original and copied values.

Show solution

Inside the class, return clone($this, ["published" => true]). Readonly properties have protected write visibility by default, so the method provides the appropriate class scope. The original stays unchanged.