Difference in write

One big difference is that you can't set class constants dynamically at runtime, which you can do with readonly properties (from the constructor).

Difference in read

There's also a big difference in how you access the two. Unless the property is static, you will need to have an instance (and all instances can have different values), while constants can always be access without an instance.

Props to M. Eriksson

Answer from Phil on Stack Overflow
🌐
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?

🌐
Reddit
reddit.com › r/phphelp › what’s the best practice for using the const keyword?
r/PHPhelp on Reddit: What’s the best practice for using the const keyword?
August 5, 2023 -

I’m coming from a background in C++ where my team used the const keyword whenever possible to prevent the chance of variables unintentionally being modified. Transitioning to PHP, I’m having a hard time understanding when to use the const keyword. I want to use it all the time like I did with C++ but naming const variables all in uppercase seems to hurt the code readability.

Do PHP developers just not use the const keyword a lot or maybe not name them all in uppercase? As a side note, is there a good open source PHP repository that I could use as a reference for the best practices for developing in PHP?

🌐
Webmobtuts
webmobtuts.com › home › backend development › php 8.1 readonly properties and const
PHP 8.1 Readonly Properties and Const - Webmobtuts
April 18, 2023 - Can’t set class constant at runtime inside the constructor or from another method in contrast to readonly property.
🌐
How-To Geek
howtogeek.com › home › programming › how to use readonly properties in php 8.1
How to Use Readonly Properties in PHP 8.1
July 30, 2021 - Unlike regular properties, readonly properties aren't allowed to have a default value in their definition: ... . You can't change its value after initialization, so the property is effectively a constant.
Top answer
1 of 5
5

Directly answering your question: No, you cannot mark regular properties as readonly. If you want to set primitive types (except array), that will never change, you should use constants

const QWE = '666';

That doesn't work for objects and arrays. I see two (lets say) "solutions"

  1. Use Getter

    private $qwe;
    public function getQwe() { return $this->qwe; }
    protected function setQwe($value) { $this->qwe = $value; }
    

    I don't like them very much ("Properties define the state, not the behavior, like methods do"). You always get twice as much additional methods as properties and if you have many properties, this will extremely blow up your class. However, it's as far as I can see the only way to implement what you want to achieve.

  2. Trust your users ;) Comment your property and say something like "If you change this value, probably something will break and its your very own fault".

    /**
     * QWE
     *
     * This property should be treatened as "readonly". If you change this value
     * something scary will happen to you.
     *
     * @readonly
     * @var string
     */
    public $qwe = '666';
    

    Its not great, but at least you can say "I told you".

2 of 5
3

Readonly properties were introduced in PHP 8.1, but static readonly properties are not supported.

From the RFC:

Readonly static properties are not supported. This is a technical limitation, in that it is not possible to implement readonly static properties non-intrusively. In conjunction with the questionable usefulness of readonly static properties, this is not considered worthwhile at this time.

However you can declare a static function to more or less get the same end result.

public static function getType(): string
{
    return 'Duck';
}
🌐
Reddit
reddit.com › r/php › readonly properties have been accepted for php 8.1 🎉
r/PHP on Reddit: Readonly properties have been accepted for PHP 8.1 🎉
July 15, 2021 - Immutable just means it can't be ... therefore can differ from instance to instance. A constant can only be one specific value and is the same for all objects instantiated....
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.

Find elsewhere
🌐
PHP
php.net › manual › en › language.oop5.properties.php
PHP: Properties - Manual
They are defined by using at least one modifier (such as Visibility, Static Keyword, or, as of PHP 8.1.0, readonly), optionally (except for readonly properties), as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value.
🌐
dailycomputerscience
dailycomputerscience.com › post › complete-guide-on-readonly-properties-in-php
Complete Guide on Readonly Properties in PHP
October 11, 2024 - They promote safer code and better data encapsulation, especially in object models with constant values or data that shouldn’t change after initialization. ... Let's look at the syntax to define a readonly property in a class. Here's how you can declare a readonly property in PHP 8.1+
🌐
PHP.Watch
php.watch › versions › 8.1 › readonly
Readonly Properties - PHP 8.1 • PHP.Watch
Read-only property values can only be set from within the class itself, either from the constructor or another method. Once set, no further modifications are allowed to that property, even from within the class. class User { public readonly int $uid; public function __construct(int $uid) { ...
🌐
Stitcher
stitcher.io › blog › php-81-readonly-properties
PHP 8.1: readonly properties | Stitcher.io
However, yes; I agree that it would be better if the language ensured that public properties couldn't be overwritten at all. Well, PHP 8.1 solves all these issues by introducing the readonly keyword: class BlogData { public function __construct( public readonly string $title, public readonly ...
🌐
Mark Baker's Blog
markbakeruk.net › 2021 › 11 › 30 › readonly-gotchas
ReadOnly Gotchas – A few more limitations with PHP 8.1 ReadOnly Properties | Mark Baker's Blog
November 30, 2021 - Finally! (On the inconstancy of constants) ... This is a quirk in readonly properties that baffles me: the RFC (https://wiki.php.net/rfc/readonly_properties_v2) specifies readonly objects still permit interior mutability, but i don’t understand why.
🌐
PHP Tutorial
phptutorial.net › home › php oop › php readonly properties
PHP Readonly Properties
April 7, 2025 - A readonly property doesn’t ensure the immutability of objects. Let’s see the following example. First, define a UserProfile class that has two properties name and phone: <?php class UserProfile { public function __construct(private string $name, private string $phone) { } public function changePhone(string $phone) { $this->phone = $phone; } }Code language: PHP (php)
🌐
Reddit
reddit.com › r/php › readonly classes in php 8.2
r/PHP on Reddit: Readonly classes in PHP 8.2
October 26, 2022 - Additionally, you'd need basically all properties present as arguments in __construct. Lastly, default values on properties will – with readonly – be equivalent to constants (except constants cannot be typed).
🌐
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 - There are some important notes to remember about readonly properties in PHP. You can only apply readonly modifier on typed properties . A readonly property without type constraints can be created using the Mixed type.
🌐
TutorialsPoint
tutorialspoint.com › explain-the-difference-between-const-and-readonly-keywords-in-chash
Explain the difference between const and readonly keywords in C#
PHP · Selected Reading · UPSC IAS Exams Notes · Developer's Best Practices · Questions and Answers · Effective Resume Writing · HR Interview Questions · Computer Glossary · Who is Who · CsharpServer Side ProgrammingProgramming · In C#, both the const and readonly keywords are used to define immutable values which cannot be modified once they are declared.
🌐
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 :)

🌐
Dev Lateral
devlateral.com › home › guides › php › what are php readonly properties and classes?
What are PHP Readonly Properties and Classes? | Dev Lateral
November 7, 2023 - In the PHP code example below we have a class called "Foo". It has one property of "name" which has been set to readonly. This means, on initialisation, the property will get set and then will be unable to be changed throughout its lifetime. Instead of using a "setter" function, we're setting the property on the class' construct (when you first initialise the class).