外感是什么意思| 斩金念什么| 动脉ct主要检查什么| 一什么地| 梅花表属于什么档次| 寄托是什么意思| 乙肝表面抗体阳性是什么意思| 情绪上来像发疯一般是什么病| 维生素B3叫什么名字| 爱有什么用| 金匮肾气丸主治什么病| 小孩拉稀吃什么药| b超检查什么| 什么牛什么毛| 外公的妈妈叫什么| 晴空万里什么意思| 哈伦裤配什么上衣好看| 缓苗是什么意思| 幽门螺旋杆菌有什么症状| 刷题是什么意思| 昔字五行属什么| 达克宁栓治疗什么妇科病| 莲是什么结构的字| 眼睛模糊流泪用什么药| 1962年属什么| 阴道镜是检查什么的| g50是什么高速| 垂盆草长什么样| 阴阳失调是什么意思| 蛋白粉吃了有什么好处| 女方什么人不能送亲| 行长是什么级别| 薜丁山是什么生肖| 清洁度111是什么意思| 卧底是什么意思| 脂溢性脱发是什么意思| 什么叫靶向治疗| 大便有点绿色是什么原因| 右耳朵热代表什么意思| 婚煞是什么意思| 一热就咳嗽是什么原因| 肾宝片有什么副作用吗| 什么东西越洗越脏脑筋急转弯| 离婚要什么手续和证件| 70年产权是从什么时候开始算| 红肉指的是什么肉| 89年五行属什么| 雪梨百合炖冰糖有什么功效| 唇炎用什么药膏| 减肥可以吃什么零食| 温开水冲服是什么意思| 融合是什么意思| 什么目什么身| 神经性呕吐是什么症状| 义务兵是什么意思| 地黄长什么样子图| 羊的尾巴有什么作用| 发改委主任什么级别| 头抖动是什么病| 富三代是什么意思| 卡马西平片是什么药| 狗尾巴草的花语是什么| 壑是什么字| 高铁上不能带什么东西| hpv是指什么| 三双是什么意思| 胎动频繁是什么原因| 鹅蛋什么人不能吃| 空调管滴水是什么原因| 流感为什么晚上会比白天严重| 上传下达是什么意思| 梦到甘蔗代表什么预兆| 根管治疗是什么意思| 高温中暑吃什么药| 宇五行属性是什么| 经期可以喝什么| 吃什么减肥最好最快| 西瓜坏了是什么样| 50岁眼睛模糊吃什么好| 5月11日什么星座| dvf是什么品牌| 4月11号是什么星座| 梦到孩子丢了是什么征兆| 食禄痣是什么意思| 人事代理什么意思| 在干什么| 1972年五行属什么| 鸽子拉水便是什么原因| 孕前检查一般有什么项目| qa是什么| 姨妈疼吃什么止疼药| 脸上反复长痘是什么原因| 骨折和骨裂有什么区别| 大学校长什么级别| 一毛不拔是什么动物| 獭尾肝是什么病| 被利用的信任是什么歌| 豆芽菜是什么意思| 吃什么可以抗衰老| 合欢树为什么叫鬼树| 宝宝睡眠不好是什么原因| 藏青色是什么颜色| 静脉曲张 看什么科| 身份证号最后一位代表什么| 飞行员妻子有什么待遇| 双鱼座跟什么星座最配| 什么原因造成耳鸣| 解表药是什么意思| 低密度脂蛋白胆固醇高是什么意思| 什么是优质蛋白食物| 地铁什么时候停运| 玉势是什么| 太阳绕着什么转| 信奥是什么| 孩子手抖是什么原因| 乙肝肝炎表面抗体阳性是什么意思| 理化检验主要检验什么| 3.28是什么星座| 60岁是什么之年| 人吸了甲醛有什么症状| 什么丰富| 别出心裁是什么意思| 单核细胞偏低是什么意思| 多囊卵巢是什么| 塔罗牌能算什么| 小孩风寒感冒吃什么药| 国家电网是什么单位| 浑圆是什么意思| 梦见剪头发是什么意思| 4.6什么星座| 冬瓜有什么功效和作用| 口我什么意思| 人造石是什么材料做的| 13朵玫瑰代表什么意思| 飞亚达手表什么档次| 气阴两虚吃什么中成药| 羊奶和牛奶有什么区别| 碱性磷酸酶偏高吃什么能降下来呢| 什么是法西斯| 总胆固醇高是什么原因| 白带过氧化氢阳性是什么意思| 甲亢多吃什么食物比较好| 喝葡萄糖有什么功效与作用| 623是什么意思| 亮丽是什么意思| peni是什么意思| 手足是什么意思| 妈妈是什么意思| 为什么舌头老是有灼烧感| 念叨是什么意思| 被利用的信任是什么歌| 什么东西不能一起吃| lg是什么| 风雨雷电代表什么生肖| 梨状肌综合征挂什么科| 比细菌还小的东西是什么| aaa是什么意思| 大腿后侧疼痛什么原因| 吃什么补充维生素| 办护照需要什么| 什么不什么当| 纤维灶是什么意思| 怀挺是什么意思| 66岁生日有什么讲究| 大便黑绿色是什么原因| 虾青素有什么作用| 看输卵管是否堵塞做什么检查| bossini是什么牌子| 公立医院是什么意思| 日龙包什么意思| 咽炎吃什么药好| 甲子日是什么意思| 口水多吃什么药好得快| 什么情况下需要做宫腔镜| 烟酰胺有什么作用| 早入簧门姓氏标什么意思| 孕妇做糖筛是检查什么| pop是什么意思| 胎膜早破是什么原因引起的| 舌头有点麻是什么病的前兆| 小孩支气管炎吃什么药| 什么是对食| 肠化是什么意思| 霍光和卫子夫什么关系| 卡替治疗是什么意思| 晚上睡觉出汗是什么原因| 脂肪肝适合吃什么水果| 右眼袋跳动是什么原因| 饿了吃什么不胖| 柚子什么时候成熟| 入睡困难吃什么中成药| 826是什么意思| 肌肉痛是什么原因| 什么药一吃就哑巴了| 3.22什么星座| 补牙属于口腔什么科| 更迭是什么意思| 吃什么补充维生素d| 什么补肾壮阳最好| 全血铅测定是什么意思| 46是什么意思| 海凉粉是什么做的| 喉咙痛是什么原因引起的| 龙是什么命| 北肖指什么生肖| 你真狗是什么意思| 狗是什么生肖| 什么人每天靠运气赚钱| 须尽欢什么意思| 分泌物多是什么原因| 智齿肿痛吃什么药| 青光眼是什么| 民营企业和私营企业有什么区别| 女性血常规都检查什么| 狼狈是什么动物| 滴虫性阴炎有什么症状表现| 孩子注意力不集中缺什么微量元素| 什么生肖晚上不睡觉| 家家酒是什么意思| 四季春茶属于什么茶| 五十而知天命是什么意思| 肠手术后吃什么恢复快| 儿童脾胃不好吃什么调理脾胃| 什么叫夏至| 拍大腿内侧有什么好处| 什么是实性结节| 牙齿冷热都疼是什么原因| 夏天适合吃什么菜| 马蜂吃什么| 尿素是什么肥| 706代血浆又叫什么| 反酸是什么症状| 阿司匹林什么时间吃最好| 蝉喜欢吃什么| 猫咪呕吐吃什么药可以解决| 大油边是什么| 人体的三道防线是什么| 水痘有什么症状| 南京为什么那么多梧桐树| 内讧是什么意思| 头大是什么原因造成的| 何五行属什么| 全身痒但是身上什么都没有| soe咖啡是什么意思| 附子理中丸治什么病| 为什么叫中国| 贝伐珠单抗是什么药| 在家做什么赚钱| 餐标是什么意思| 欧米茄算什么档次| 床头朝向有什么讲究| 左旋肉碱是什么| 缺黄体酮会有什么症状| 小媳妇是什么意思| 积分落户是什么意思| ml什么意思| 五行金是什么颜色| 时柱比肩是什么意思| 吐舌头是什么意思| 一什么不什么| 佃农是什么意思| 画饼充饥是什么意思| 婴儿喝什么牌奶粉好| 紧急避孕药什么时候吃最有效| 百度
Table of Contents
What Are Readonly Properties?
Enforcing Deep Immutability
? Solution: Wrap arrays in ArrayObject or use immutable collections
Best Practices for Immutable Objects
Limitations and Gotchas
Summary
Home Backend Development PHP Tutorial Building Immutable Objects in PHP with Readonly Properties

心功能不全是什么意思

Jul 30, 2025 am 05:40 AM
php read-only attribute

百度 2008年起,中国美术学院启动国美之路学术工程,以展览、出版、论坛等多种形式对各优势学科、专业进行深入的历史梳理,将国美各专业纳入中国现代美术史与教育史中的大背景中探究其源流、脉络以及独特的价值观与方法论。

Readonly properties in PHP 8.2 can only be assigned once in the constructor or at declaration and cannot be modified afterward, enforcing immutability at the language level. 2. To achieve deep immutability, wrap mutable types like arrays in ArrayObject or use custom immutable collections such as TagCollection that prevent direct state changes. 3. Best practices include initializing all properties in the constructor, avoiding setters, returning new instances via withX() methods, using final classes, and disabling cloning to prevent mutation. 4. Limitations include lack of support for dynamic properties, no deep freezing of objects or arrays, and the need for manual handling of nested mutability. 5. Despite these gotchas, combining readonly properties with value objects and functional patterns enables safe, predictable, and thread-safe immutable objects using only native PHP features, making it easier to build robust domain models without external libraries.

Building Immutable Objects in PHP with Readonly Properties

In PHP 8.2, a powerful feature was introduced: readonly properties. This makes it much easier to build immutable objects — objects whose state cannot be changed after creation. Immutable objects are valuable because they’re predictable, thread-safe, and reduce bugs caused by unintended state changes.

Building Immutable Objects in PHP with Readonly Properties

Here’s how you can use readonly to create truly immutable value objects in PHP.


What Are Readonly Properties?

A readonly property can only be assigned once — either at the declaration or inside the constructor. After that, it cannot be modified.

Building Immutable Objects in PHP with Readonly Properties
class User
{
    public function __construct(
        public readonly string $id,
        public readonly string $email
    ) {}
}

Once set, $user->email = 'new@example.com'; will throw a Cannot modify readonly property error.

This enforces immutability at the language level — no need to rely on conventions or magic methods.

Building Immutable Objects in PHP with Readonly Properties

Enforcing Deep Immutability

Using readonly on its own doesn’t guarantee full immutability if your property holds a mutable type like an array or object. For example:

class BlogPost
{
    public function __construct(
        public readonly string $title,
        public readonly array $tags
    ) {}
}

$post = new BlogPost('PHP 8.2', ['php', 'immutable']);
$post->tags[] = 'readonly'; // This works! Array content can still change.

To prevent this, you need to defend against mutation of arrays and objects.

? Solution: Wrap arrays in ArrayObject or use immutable collections

class BlogPost
{
    /**
     * @var readonly ArrayObject<int, string>
     */
    public readonly ArrayObject $tags;

    public function __construct(
        public readonly string $title,
        array $tags
    ) {
        $this->tags = new ArrayObject($tags);
        $this->tags->setFlags(ArrayObject::ARRAY_AS_PROPS);
        $this->tags->getFlags() & ~ArrayObject::STD_PROP_LIST;
    }
}

Now you can read $post->tags, but modifying it (e.g., $post->tags[] = 'hack') will fail because the property itself is readonly — you can't reassign it, and if you expose methods to manipulate internal state, you control them explicitly.

Alternatively, consider using value objects for collections:

/**
 * @implements \IteratorAggregate<string>
 */
class TagCollection implements \IteratorAggregate
{
    private array $tags;

    public function __construct(array $tags) {
        $this->tags = array_values(array_unique($tags));
    }

    public function getIterator(): \Traversable
    {
        return new \ArrayIterator($this->tags);
    }

    public function withAdded(string $tag): self
    {
        return new self([...$this->tags, $tag]);
    }
}

class BlogPost
{
    public function __construct(
        public readonly string $title,
        public readonly TagCollection $tags
    ) {}
}

Now immutability is preserved: you can’t modify $post->tags, and even if you iterate it, any changes require creating a new instance.


Best Practices for Immutable Objects

To build robust immutable objects in PHP:

  • ? Use readonly on all properties
  • ? Initialize everything in the constructor
  • ? Avoid public setters or mutator methods
  • ? Return new instances instead of modifying state
  • ? Use final classes to prevent unintended overrides
  • ? Consider using __clone() to prevent accidental mutation via cloning
final class User
{
    public function __construct(
        public readonly string $id,
        public readonly string $name,
        public readonly string $email
    ) {}

    // Instead of setEmail(), return a new instance
    public function withEmail(string $email): self
    {
        return new self($this->id, $this->name, $email);
    }

    // Prevent cloning (optional)
    public function __clone()
    {
        throw new \BadMethodCallException('Cloning is disabled for immutable object.');
    }
}

Usage:

$user = new User('123', 'Alice', 'alice@example.com');
$updated = $user->withEmail('alice@new.com'); // New instance
// $user remains unchanged

Limitations and Gotchas

  • readonly only works on class properties — not dynamic properties
  • You can’t assign to a readonly property outside the constructor, even from within the class
  • Objects and arrays assigned to readonly props aren't deeply frozen — you must handle that yourself
  • PHP doesn’t have built-in immutable arrays, so you’ll need wrappers or custom logic

Summary

With readonly in PHP 8.2 , building immutable objects is now practical and safe. Combine readonly properties with defensive copying, value objects, and functional-style methods (withX() instead of setX()) to create clean, predictable domain models.

You don’t need a framework or library — just good design and PHP’s built-in features.

Basically: declare it once, keep it safe.

The above is the detailed content of Building Immutable Objects in PHP with Readonly Properties. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles
超敏c蛋白反应高是什么原因 葡萄上的白霜是什么 左侧肚脐旁边疼是什么原因 大便每天四五次是什么病 故宫为什么叫紫禁城
胃胀不舒服吃什么药 送什么礼品好 月黑风高什么意思 大腿根部痛是什么原因 bbc是什么意思
产前诊断是检查什么 prr是什么意思 557是什么意思 女的学什么手艺最赚钱 1993年五行属什么
折耳根是什么 男人占有欲强说明什么 晕轮效应是什么意思 白带是什么样的 缺维生素a吃什么食物
1927年中国发生了什么hcv7jop5ns2r.cn 做梦来月经了什么预兆hcv8jop6ns8r.cn 三文鱼又叫什么鱼hcv9jop5ns6r.cn 花中隐士是什么花bfb118.com 日文是什么字hcv9jop4ns8r.cn
白色加红色等于什么颜色hcv9jop2ns1r.cn 2030年属什么生肖520myf.com 正常尿液是什么味道hcv9jop0ns3r.cn 是什么数学符号hcv9jop4ns0r.cn 脂肪肝是什么原因造成的hcv8jop3ns0r.cn
但闻人语响的但是什么意思hcv8jop4ns1r.cn 头痛什么原因hcv8jop0ns8r.cn 低聚木糖是什么hcv9jop1ns7r.cn 无忧是什么意思hcv8jop9ns2r.cn 人出现幻觉是什么原因hcv9jop6ns3r.cn
血管痉挛是什么原因引起的hcv7jop4ns7r.cn 高血糖能吃什么水果ff14chat.com 不适随诊是什么意思hcv8jop3ns7r.cn 头发打结是什么原因hcv8jop5ns8r.cn 阑尾炎不能吃什么食物hcv9jop4ns2r.cn
百度