prewk/option

受 Rust 启发的 PHP 选项对象


README

这是一个与 Rust 的 Option 类型 大致相同的 API 的 PHP 实现。

版本信息

4.x.x 版本需要 PHP 8.1 以上。如果你同时使用此库和 Result 库,请确保版本匹配。

安装

composer require prewk/option

使用方法

use Prewk\Option;
use Prewk\Option\{Some, None};

function findSomething(): Option {
    // ...
    if ($foundSomething) {
        return new Some($thing);
    } else {
        return new None;
    }
}

function findSomethingElse(): Result {
    // ...
    if ($foundSomething) {
        return new Some($thing);
    } else {
        return new None;
    }
}

// Fallback to value
$value = findSomething()->unwrapOr(null);

// Fallback to option and throw an exception if both fail
$value = findSomething()->or(findSomethingElse())->unwrap();

// Throw custom exception on missing thing (None)
$value = findSomething()->expect(new Exception("Oh noes!"));

许可证

MIT & Apache 2.0