You can do it like this:

class Example {
    private $__readOnly = 'hello world';
    function __get($name) {
        if($name === 'readOnly')
            return $this->__readOnly;
        user_error("Invalid property: " . __CLASS__ . "->$name");
    }
    function __set($name, $value) {
        user_error("Can't set property: " . __CLASS__ . "->$name");
    }
}

Only use this when you really need it - it is slower than normal property access. For PHP, it's best to adopt a policy of only using setter methods to change a property from the outside.

Answer from too much php on Stack Overflow
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ language.oop5.properties.php
PHP: Properties - Manual
As of PHP 8.1.0, a property can be declared with the readonly modifier, which prevents modification of the property after initialization. Prior to PHP 8.4.0 a readonly property is implicitly private-set, and may only be written to from the same ...
๐ŸŒ
PHP.Watch
php.watch โ€บ versions โ€บ 8.1 โ€บ readonly
Readonly Properties - PHP 8.1 โ€ข PHP.Watch
The $user object itself can change, and the readonly property does not prevent modifications to the object itself. If the immutability is required, make sure to clone the object prior to assigning: class Post { public readonly User $author; public function __construct(User $author) { - $this->author = $author; + $this->author = clone $author; } }
Discussions

When should one use read-only properties / classes?
"Excuse"?!? Use readonly whenever you can. You should have a good reason when you do not use it. ... Or an application that started many years ago. ;) More on reddit.com
๐ŸŒ r/PHP
22
12
July 1, 2024
What's the benefit of readonly properties over constants?
Constants have to be "compile time" defined (think hardcoded by hand), read-only fields can be set once with any value during runtime (say a field from db). More on reddit.com
๐ŸŒ r/PHP
18
11
November 16, 2024
oop - What is the benefit of readonly in PHP 8.1? - Stack Overflow
In PHP 8.1, the readonly keyword is now available. I am curious about its purpose. Is it intended to assist the editor in recognizing that a property is solely readonly, to aid the client in More on stackoverflow.com
๐ŸŒ stackoverflow.com
Can we revive the readonly properties discussion?

Property accessors is a much better way to go than adding a readonly keyword. It's a shame that RFC failed. I don't know the reasons but you could try searching the mailing list to find any discussions around the time (try externals.io if they have stuff from back then).

More on reddit.com
๐ŸŒ r/PHP
43
29
March 5, 2015
๐ŸŒ
Reddit
reddit.com โ€บ r/php โ€บ when should one use read-only properties / classes?
r/PHP on Reddit: When should one use read-only properties / classes?
July 1, 2024 -

I discovered this feature a few weeks ago and end up using it a lot in my DTOs (most times they end up being read-only classes).

Right now, the only other use case I have for it is for class properties injected via dependency injection, which I believe should probably never be changed to anything else than what it was first instantiated as.

I'm not sure if the DI properties is a good excuse for using read-only, or if there are other use cases I might have missed, which is why I'm asking how you guys use it :)

๐ŸŒ
Stitcher
stitcher.io โ€บ blog โ€บ php-81-readonly-properties
PHP 8.1: readonly properties | Stitcher.io
The reason that it is allowed for promoted properties, is because the default value of a promoted property isn't used as the default value for the class property, but only for the constructor argument. Under the hood, the above code would transpile to this: class BlogData { public readonly string $title; public function __construct( string $title = 'Readonly properties', ) { $this->title = $title; } }
๐ŸŒ
dailycomputerscience
dailycomputerscience.com โ€บ post โ€บ complete-guide-on-readonly-properties-in-php
Complete Guide on Readonly Properties in PHP
October 11, 2024 - We'll also cover practical examples and use cases with the latest PHP syntax. A readonly property is a property in a PHP class that can only be assigned once, usually during object construction. Once assigned, the value of this property cannot ...
๐ŸŒ
phpFashion
phpfashion.com โ€บ en โ€บ php-readonly-properties
The Hidden Surprises of PHP Readonly Properties ยป phpFashion
Picture this: data that's as stable as bedrock โ€“ set it once, and it stays that way forever. That's exactly what PHP 8.1 delivered with readonly properties. Think of it as giving your objects a safety vault โ€“ keeping their data secure from accidental changes.
Find elsewhere
๐ŸŒ
PHP
wiki.php.net โ€บ rfc โ€บ readonly_properties_v2
PHP: rfc:readonly_properties_v2
June 2, 2021 - Lifting the restriction in the child class could break invariants in the parent class. As such, a readonly modifier may be neither added nor removed during inheritance. It is interesting to consider how property redeclaration interacts with the restriction that initialization can only occur in the declaring class:
๐ŸŒ
DEV Community
dev.to โ€บ xxzeroxx โ€บ php-8-news-readonly-properties-2me1
PHP 8 news: Readonly properties - DEV Community
March 24, 2024 - In PHP 8.1, readonly properties were introduced, which allow you to declare class properties that can only be set once during object initialization and cannot be modified thereafter.
๐ŸŒ
Medium
kvnc-inc.medium.com โ€บ php-8-1-new-features-readonly-properties-9994fdffd594
Php 8.1 New Features โ€” Readonly Properties | by Backend Developer | Medium
January 13, 2022 - With new version of PHP we have a new feature named Readonly properties. Readonly properties are init and set value just once and we can not change its value. This protects unwanted value changes from anywhere in codebase.
๐ŸŒ
Stitcher
stitcher.io โ€บ blog โ€บ readonly-classes-in-php-82
Readonly classes in PHP 8.2 | Stitcher.io
October 25, 2022 - PHP 8.2 adds a new way of declaring classes: you can make them readonly. In practice, it means that all properties of that class will be readonly.
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ power-php-8-public-readonly-properties-christian-vermeulen
The power of PHP 8 public readonly properties ๐Ÿ’ช
August 30, 2022 - Instead of just declaring the property's access, why not also declare its mutability? We can now add the "readonly" keyword to make sure the property can not be changed during runtime, making the property immutable.
๐ŸŒ
Medium
medium.com โ€บ @arifhossen.dev โ€บ mastering-readonly-properties-and-classes-in-php-a-comprehensive-guide-for-beginner-cfa075a62784
Mastering Readonly Properties and Classes in PHP: A Comprehensive Guide for Beginner โ€” 2025 | by Arif Hossen | Medium
January 9, 2025 - These features, introduced in PHP 8.1 and 8.2, provide developers with enhanced control over object immutability and data integrity. ... Readonly properties are class attributes set only once, typically during object construction.
๐ŸŒ
Reddit
reddit.com โ€บ r/php โ€บ what's the benefit of readonly properties over constants?
r/PHP on Reddit: What's the benefit of readonly properties over constants?
November 16, 2024 -

After all, the overlap is so big that I struggle to see why they were introduced.

If you want a property to be immutable after assignment, a constant does that, too. That's also why constants being public is fine.

So, I would have found readonly more useful, if I was allowed to always re-assign them from inside the class that defined them. Then they would work like a private property that only has a getter but no setter - which I find convenient. It's the job of the class to manage its state, so I don't see why you shouldn't be allowed to re-assign them from inside when constants already exist.

Care to enlighten me?

๐ŸŒ
Ash Allen Design
ashallendesign.co.uk โ€บ blog โ€บ readonly-classes-and-properties-in-php
Readonly Classes and Properties in PHP | Ash Allen Design
March 19, 2024 - It allows us to prevent properties from being changed after they have been set and can give us confidence we aren't accidentally changing a property we shouldn't. PHP 8.2 then introduced the ability to make entire classes readonly.
Top answer
1 of 1
14

readonly properties allow you to create immutable objects, or at the very least immutable properties (since 8.2 we also have readonly for classes, which allow creating immutable objects without having to apply the keyword to each of the class properties).

That way, you can be sure that a value won't be changed by accident after being initialized, throughout the object's life.

It's a very similar concept to constants (set via const or define), albeit with two important differences:

  • constants need to be defined on "compilation" time, whereas readonly properties will be set during runtime, usually during on object instantiation (so multiple instances will be able to hold different values*)
  • constants live in the global scope; and in case of class constants, their value is tied to the class and not to the instance.

You could achieve the same with a private property only accessible via a getter. E.g., in "the olden days":

class Foo {

    private DateTimeImmutable $createAt;

    public function __construct() {
        $this->createdAt = new DateTimeImmutable();
    }

    public function getCreatedAt(): DateTimeImmutable
    {
        return $this->createdAt;
    }
}

$f = new Foo();
echo $f->getCreatedAt()->format('Y-m-d H:i:s');

The only problem with this is that it requires a lot of boilerplate code.

With PHP 8.1, almost the same could be achieved by doing:

class Foo
{

    public function __construct(
        public readonly DateTimeImmutable $createdAt = new DateTimeImmutable()
    )
    { }

}

$f = new Foo();
echo $f->createdAt->format('Y-m-d H:i:s')

And since PHP 8.2 add readonly classes, it gets even better, since one can do:

readonly class Foo
{

    public function __construct(
        public string $name,
        public DateTimeImmutable $createdAt = new DateTimeImmutable()
    )
    { }

}

And now both Foo::name and Foo::createdAt are readonly, and can only be set during object instantiation.

๐ŸŒ
DEV Community
dev.to โ€บ neloyahmed โ€บ the-story-of-readonly-classes-and-properties-in-php-1l02
The story of readonly classes and properties in php - DEV Community
December 20, 2022 - You can initialize the readonly property once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an Error exception. <?php class User { public readonly string $name; } $john = new User; // Illegal initialization outside of ...
๐ŸŒ
PHP Tutorial
phptutorial.net โ€บ home โ€บ php oop โ€บ php readonly properties
PHP Readonly Properties
April 7, 2025 - The readonly properties allow you to define properties that can be only initialized once within the class.
๐ŸŒ
Alex Web Develop
alexwebdevelop.com โ€บ home โ€บ php readonly properties: how to use them
PHP Readonly Properties: How to Use Them - Alex Web Develop
August 6, 2023 - Using readonly for this property makes perfect sense, because you donโ€™t want this value to change. This specific account is either an admin or not. Depending on whether admin is true or false, your PHP script performs different operations such as displaying a different HTML output and authorizing ...