A PHP implementation of Rust's Option type with roughly the same API.
Version 4.x.x requires PHP 8.1+. Make sure you match the versions for this and the Result library if you use both.
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