Menu

← Back to property.*

Error Identifier: property.readOnlyAssignNotInConstructor

Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.

Code example #

<?php declare(strict_types = 1);

class User
{
	public readonly string $name;

	public function __construct(string $name)
	{
		$this->name = $name;
	}

	public function rename(string $name): void
	{
		$this->name = $name;
	}
}

Why is it reported? #

A readonly property is being assigned outside of the class constructor. In PHP, readonly properties can only be initialized once, and this initialization must happen in the constructor of the declaring class (or in __unserialize). Assigning to a readonly property in any other method will cause a runtime error.

How to fix it #

Move the assignment into the constructor, or redesign the class so the readonly property does not need to change after construction:

 class User
 {
-	public readonly string $name;
+	public string $name;

 	public function __construct(string $name)
 	{
 		$this->name = $name;
 	}

 	public function rename(string $name): void
 	{
 		$this->name = $name;
 	}
 }

If immutability is desired, create a new instance instead of modifying the existing one:

 class User
 {
 	public function __construct(
 		public readonly string $name,
 	) {}

-	public function rename(string $name): void
+	public function withName(string $name): self
 	{
-		$this->name = $name;
+		return new self($name);
 	}
 }

How to ignore this error #

You can use the identifier property.readOnlyAssignNotInConstructor to ignore this error using a comment:

// @phpstan-ignore property.readOnlyAssignNotInConstructor
codeThatProducesTheError();

You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:

parameters:
	ignoreErrors:
		-
			identifier: property.readOnlyAssignNotInConstructor

Rules that report this error #

  • PHPStan\Rules\Properties\ReadOnlyPropertyAssignRule [1]

Edit this page on GitHub

Theme
A
© 2026 PHPStan s.r.o.