Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A readonly class in PHP (introduced in PHP 8.2) is a class modifier that implicitly declares all of its instance properties as readonly. Once an object of this class is instantiated and its properties are initialized, the object enforces shallow immutability. This prevents the reassignment of the properties themselves, though if a property holds a mutable object, the internal state of that referenced object can still be modified. Any attempt to reassign a property after initialization will throw an Error exception.
readonly class Configuration
{
    public function __construct(
        public string $host,
        public int $port,
        public stdClass $metadata,
    ) {}
}

$config = new Configuration('localhost', 8080, new stdClass());

// Throws Error: Cannot modify readonly property Configuration::$port
// $config->port = 9000; 

// Valid: Shallow immutability allows modification of internal state of mutable objects
$config->metadata->environment = 'production'; 

Core Mechanics and Constraints

Applying the readonly modifier to a class enforces a strict set of rules at compile-time and runtime: 1. Implicit Property Modification Every declared instance property within the class automatically inherits the readonly modifier. You do not need to explicitly declare individual properties as readonly. 2. Strict Typing Requirement All properties within a readonly class must have an explicit type declaration. Untyped properties will trigger a fatal error. If a property can accept any value, it must be explicitly typed as mixed. 3. Static Properties Forbidden A readonly class cannot declare static properties. The readonly modifier applies exclusively to instance properties, and attempting to define a static property within a readonly class will result in a fatal compile-time error. 4. Dynamic Properties Forbidden Dynamic properties are strictly prohibited on readonly classes. Additionally, a readonly class cannot be marked with the #[AllowDynamicProperties] attribute. Attempting to apply this attribute will trigger a fatal error. 5. Inheritance Restrictions The readonly state dictates strict inheritance rules. A readonly class can only be extended by another readonly class. Conversely, a standard (non-readonly) class cannot be extended by a readonly class.
Master PHP with Deep Grasping Methodology!Learn More