Skip to content

12: Change Properties on Objects Held in Constants

Update a mutable object held by a class constant. In PHP 8.6 you can write through the constant expression directly.

  • PHP 8.6 CLI. Confirm the version with php --version.
  • Review the previous chapter if you’re following the series in order.

Allow about 10 minutes for the walkthrough and exercise.

A runnable constant-object-mutation.php example.

Run the following from the root of the Code with PHP repository.

Terminal window
php code/php-8-6/12-constant-object-mutation/constant-object-mutation.php
constant-object-mutation.php
<?php
declare(strict_types=1);
final class WorkerSettings
{
public function __construct(public int $timeoutSeconds)
{
}
}
const DEFAULT_WORKER_SETTINGS = new WorkerSettings(5);
final class WorkerConfiguration
{
public const DEFAULTS = DEFAULT_WORKER_SETTINGS;
}
$sameSettings = WorkerConfiguration::DEFAULTS;
echo 'Before: ', $sameSettings->timeoutSeconds, PHP_EOL;
WorkerConfiguration::DEFAULTS->timeoutSeconds = 12;
echo 'After: ', $sameSettings->timeoutSeconds, PHP_EOL;
Before: 5
After: 12

The global constant constructs the shared object and the class constant references it. Every reference to that object can observe the new property value, so shared defaults in long-lived workers can affect later jobs. The regular property visibility and readonly rules still apply.

Clone the settings into a local variable, change the clone’s timeout, and print both timeouts. The shared instance should retain its previous value.

Continue with Build URLs and URI References from Components.