PHP 8 Intermediate OOP · 6 min read

PHP Readonly Properties

Lesson 34 of 43 in the PHP 8 learning path.

How do I stop a lesson id from being changed after construction?

A readonly property may be written once, from the constructor, and then only read.

An id that can be reassigned in the middle of a request causes the wrong row to be updated.

Syntax & Parameters

Syntax
public function __construct(public readonly int $id) {}

Example

src/LessonRef.php
<?php
declare(strict_types=1);
final class LessonRef
{
    public function __construct(
        public readonly int $id,
        public readonly string $slug,
    ) {
    }
}
function label(LessonRef $lesson): string
{
    return $lesson->id.":".$lesson->slug;
}
$lesson = new LessonRef(12, "routes");
echo label($lesson), PHP_EOL;

Expected Output

12:routes

Line-by-Line Walkthrough

  1. The class is final so a child cannot loosen the rule.
  2. id and slug are promoted constructor properties.
  3. readonly means the assignment in the constructor is the only write.
  4. label only reads the properties.
  5. The example constructs lesson 12 with slug routes.
  6. A later assignment to id would be a fatal error.
  7. Readonly does not deep-freeze an object property.
  8. The database is still the source of the id. This only protects the in-memory value.

Common Pitfalls & Security

This is easy to misuse.

  • A readonly object property can still have its inner fields changed.
  • You cannot set a readonly property from a setter later.
  • Unsetting it is also forbidden.
  • Readonly is not a security boundary against a bad SQL update.

Best Practices & Modern Standards

Use readonly for identifiers and value objects that should not change during the request.

Prefer a constructor assignment over a public property you remember not to touch.

Real-World Use

A controller builds a LessonRef from the route and passes it down. No later line can retarget the update to a different id.

Frequently Asked Questions

Can I change a readonly property?

Only by assigning it once during construction. A later write is an error.

Does it work with promotion?

Yes. public readonly int $id in the constructor is the usual form.

Can a child class write it?

A child cannot write a parent readonly property from its own scope after construction.

Is this the same as a constant?

No. Each object has its own value. A constant is one value for the class.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…