phpfn/immutable

确保不可变对象的简单助手

2.0.1 2020-11-22 21:15 UTC

This package is auto-updated.

Last update: 2024-09-23 06:07:36 UTC


README

安装

库可以被安装到任何PHP应用程序中

$ composer require phpfn/immutable

为了访问库,请确保将 vendor/autoload.php 包含在您的文件中。

<?php

require __DIR__ . '/vendor/autoload.php';

使用方法

要确保对象的不可变性,只需将您的任何方法代码包裹在闭包中即可。

可变对象示例

class Example
{
    private int $value = 42;

    public function update(int $newValue): self
    {
        $this->value = $newValue;
    
        return $this;
    }
}

使其不可变

class Example
{
    private int $value = 42;

    // Sample #1 (PHP 7.4+)
    public function with(int $newValue): self
    {
        return immutable(fn () => $this->value = $newValue);
    }
}

就是这样!