
PhpStorm 2020.3 不支持 PHP 8.1 新增的 readonly 属性语法,导致“Undefined class readonly property”错误;升级至 PhpStorm 2021.3 或更高版本即可解决。
phpstorm 2020.3 不支持 php 8.1 新增的 `readonly` 属性语法,导致“undefined class readonly property”错误;升级至 phpstorm 2021.3 或更高版本即可解决。
PHP 8.1 引入了 readonly 属性关键字,用于声明不可重新赋值的类属性,例如:
class User
{
public readonly string $name;
public readonly int $id;
public function __construct(string $name, int $id)
{
$this->name = $name; // ✅ 允许在构造函数中初始化
$this->id = $id;
}
}
然而,PhpStorm 2020.3 及更早版本并未内置对 readonly 语法的支持,因此编辑器会将其识别为非法标识符,报出类似 Undefined class 'readonly' property 的误报(实际并非运行时错误,而是 IDE 解析能力不足)。
✅ 正确解决方案:
- 升级 PhpStorm 至 2021.3 或更高版本(推荐使用最新稳定版,如 2023.x / 2024.x);
- 升级后,确保项目 PHP Language Level 设置为 PHP 8.1 或更高(File → Settings → Languages & Frameworks → PHP → Language level);
- 同时确认 CLI Interpreter 已配置为 PHP 8.1+ 版本(Settings → PHP → CLI Interpreter),以启用完整语法检查与代码补全。
⚠️ 注意事项:
-
readonly属性仅适用于类属性(不支持全局变量或函数内变量); - 初始化仅允许在构造函数中完成,且不可通过反射、
__set()或其他方式修改; -
readonly类不能被继承(即final语义隐含),若需扩展,应使用组合而非继承; - PhpStorm 2021.3 起不仅消除误报,还提供智能提示、重构支持(如一键添加
readonly)、以及对非法赋值的实时高亮警告。
升级后重启 IDE,上述语法将被正确识别,开发体验与 PHP 8.1 规范完全对齐。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










