Readonly Properties
The immutability spectrum — PHP 8.1 readonly versus how 10 languages block reassignment, and when.
C C23
#include <stdio.h>
/* C: a const member blocks writes through that struct (compiler-enforced) */
typedef struct {
const int x;
const int y;
} Point;
int main(void) {
Point p = {3, 4}; /* the only write: the initializer */
printf("%d\n", p.x + p.y);
/* p.x = 10; */ /* compile error: assignment of read-only member */
return 0;
}
7
C++ C++26
#include <cstdio>
// C++: const members are write-once — set in the member initializer list only
class Point {
public:
const int x;
const int y;
Point(int xx, int yy) : x(xx), y(yy) {} // the only legal write point
};
int main() {
Point p{3, 4};
std::printf("%d\n", p.x + p.y);
// p.x = 10; // compile error: assignment of read-only member
return 0;
}
7
C# v11.0.100
var p = new Point { X = 3, Y = 4 };
Console.WriteLine(p.X + p.Y);
// p.X = 10; // compile error: init-only property may only be set in creation
class Point {
// init-only setter (C# 9+): assignable during object creation, then sealed
public int X { get; init; }
public int Y { get; init; }
}
7
Go v1.27.4
package main
import "fmt"
// Go has no readonly: immutability is by convention — an unexported field
// plus a getter keeps outsiders from writing, but the package itself still can
type Point struct {
x, y int // unexported: invisible outside the package
}
func (p Point) Sum() int { return p.x + p.y } // read access only
func main() {
p := Point{x: 3, y: 4} // same-package code may still write freely
fmt.Println(p.Sum())
}
7
Java v27.0.1
public class Main {
// final field: one assignment, enforced by the compiler
static class Point {
final int x;
final int y;
Point(int x, int y) { this.x = x; this.y = y; }
}
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p.x + p.y);
// p.x = 10; // compile error: cannot assign a value to final variable
}
}
7
JavaScript v26.13.1
"use strict";
// JS has no readonly syntax: Object.freeze is a RUNTIME lock — the error
// surfaces only when someone actually writes (in strict mode)
const p = Object.freeze({ x: 3, y: 4 });
console.log(p.x + p.y);
try {
p.x = 10; // silently ignored in sloppy mode; TypeError in strict mode
} catch (e) {
console.log("TypeError: " + e.message);
}
7 TypeError: Cannot assign to read only property 'x' of object '#<Object>'
PHP v8.6.0
class Point {
public function __construct(
public readonly int $x, // promoted + readonly: writable exactly once
public readonly int $y,
) {}
}
$p = new Point(3, 4);
echo $p->x + $p->y, "\n";
try {
$p->x = 10; // second write: Error, even with the same value
} catch (Error $e) {
echo "Error: ", $e->getMessage(), "\n";
}
7 Error: Cannot modify readonly property Point::$x
Python v3.15.2
class Point:
def __init__(self, x, y):
self._x = x
self._y = y
@property
def x(self): # read-only property: a getter with no setter
return self._x
@property
def y(self):
return self._y
p = Point(3, 4)
print(p.x + p.y)
try:
p.x = 10 # raises AttributeError: property 'x' has no setter
except AttributeError as e:
print("AttributeError:", e)
7 AttributeError: property 'x' of 'Point' object has no setter
Rust v1.99.1
// Rust immutability is the DEFAULT: a plain binding is compile-time frozen;
// only `let mut` may be reassigned — nothing to check at runtime
fn main() {
let x = 3;
let y = 4;
println!("{}", x + y);
// x = 10; // compile error: cannot assign twice to immutable variable
let mut m = 1;
m = 10; // opt-in mutability works
println!("{}", m);
}
7 10
TypeScript v26.13.1
// TS readonly: a compile-time-only modifier — erased in the JS output;
// it guards your codebase, not the runtime
class Point {
readonly x: number;
readonly y: number;
constructor(x: number, y: number) {
this.x = x; // the only legal write point
this.y = y;
}
sum(): number {
return this.x + this.y;
}
}
const p = new Point(3, 4);
console.log(p.sum());
// p.x = 10; // compile error: cannot assign to readonly property
7
Language differences
C: a const struct member (example): writable once by the initializer, later assignments blocked at compile time; deep object-graph immutability needs const on every member.
C++: const members can only be written once, in the constructor's initializer list (example); compile-time constraint; pass const Point& / const Point* for whole-object read-only.
C#: a pair — field-level readonly (constructor-writable) plus the property-level init accessor (C# 9+, writable during creation, example); compile-time constraint; record + with expressions build new objects instead of mutating.
Go: no readonly — immutability is convention: an unexported field plus a getter keeps outsiders out (example) while the package itself writes freely; the standard library has no freezing.
Java: final fields (example): one constructor write, compiler-enforced; no built-in runtime object-graph freeze — deep immutability needs immutable-class design.
JavaScript: no readonly syntax — Object.freeze is a runtime lock (example): writes throw TypeError in strict mode and fail silently otherwise; shallow freeze, recurse for deep.
PHP: the 8.1+ readonly property (example): a second write throws Error (same value included); typed properties only; readonly classes arrive in 8.2, __clone re-initialization in 8.3, implicit protected(set) in 8.4, and default values in 8.6; mind interior mutability — the stored object itself stays mutable.
Python: no readonly — the convention is a _x privacy hint plus a read-only @property getter (example): assignment raises AttributeError; it is convention-level protection and p._x = 10 bypasses it.
Rust: immutability is the default (example): plain bindings freeze at compile time, let mut opts in; the ownership system also rules out aliasing mutable references, so it goes further than most.
TypeScript: readonly is compile-time-only (example): erased in the JS output with no runtime guard (fall back to Object.freeze for that); it protects the codebase, not memory.