12: Change Properties on Objects Held in Constants
Overview
Section titled “Overview”Update a mutable object held by a class constant. In PHP 8.6 you can write through the constant expression directly.
Prerequisites
Section titled “Prerequisites”- 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.
What You’ll Build
Section titled “What You’ll Build”A runnable constant-object-mutation.php example.
Step 1: Run the example (~5 min)
Section titled “Step 1: Run the example (~5 min)”Run the following from the root of the Code with PHP repository.
php code/php-8-6/12-constant-object-mutation/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;Expected Result
Section titled “Expected Result”Before: 5After: 12Why It Works
Section titled “Why It Works”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.
Exercise
Section titled “Exercise”Clone the settings into a local variable, change the clone’s timeout, and print both timeouts. The shared instance should retain its previous value.
Wrap-up
Section titled “Wrap-up”Continue with Build URLs and URI References from Components.