yceruto/option-type

An Option type that represents an optional value

Fund package maintenance!
yceruto

v1.0.3 2024-04-19 21:09 UTC

This package is auto-updated.

Last update: 2024-04-30 03:07:55 UTC


README

Latest Stable Version Unstable License PHP Version Require

The Option class 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.

/**
 * @return int|null
 */
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. This is where the Option class comes in handy: it makes you deal with the possibility of a missing value, 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 None 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 Option::some(), meaning it includes a value, while none() is the same as Option::none(), indicating it's empty.

Documentation

License

This software is published under the MIT License