定制 yceruto/option-type 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yceruto/option-type

最新稳定版本:v1.0.6

Composer 安装命令:

composer require yceruto/option-type

包简介

An Option type that represents an optional value

README 文档

README

Latest Stable Version Unstable License PHP Version Require

The Option type represents a value that might or might not be there. It's all about null safety in PHP!

Note

Inspired by Rust's Option type and other languages like Scala, Swift, F#, etc.

Installation

composer require yceruto/option-type

Handling the presence or absence of a value with null

In PHP, denoting the absence of a value is done with null, e.g. when a divide function returns null if the divisor is 0.

function divide(int $dividend, int $divisor): ?int
{
    if (0 === $divisor) {
        return null;
    }

    return intdiv($dividend, $divisor);
}

function success(int $result): string {
    return sprintf('Result: %d', $result);
}

$result = divide(10, 2);

echo success($result);

Can you spot the issue in this code? Apparently, everything is fine until you try to divide by zero. The function will return null, and the success() function will throw a TypeError because it expects an int value, not null.

The issue with this approach is that it's too easy to overlook checking if the value is null, leading to runtime errors, and this is where the Option type comes in handy: it always forces you to deal with the null case.

Handling the presence or absence of a value with Option

Options often work with pattern matching to check if there’s a value and act accordingly, always making sure to handle the null case.

use Std\Type\Option;
use function Std\Type\Option\none;
use function Std\Type\Option\some;

/**
 * @return Option<int>
 */
function divide(int $dividend, int $divisor): Option
{
    if (0 === $divisor) {
        return none();
    }

    return some(intdiv($dividend, $divisor));
}

function success(int $result): string {
    return sprintf('Result: %d', $result);
}

// The return value of the function is an Option
$result = divide(10, 2);

// Pattern match to retrieve the value
echo $result->match(
    // The division was valid
    some: fn (int $v) => success($v),
    // The division was invalid
    none: fn () => 'Division by zero!',
);

Tip

You can use the functions some() and none() as quick ways to create an Option instance. some() is just like new Some(), meaning it includes a value, while none() is the same as new None(), indicating it is missing a value.

Documentation

License

This software is published under the MIT License

统计信息

  • 总下载量: 14
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 15
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 15
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-04-18