This library implements two monadic types for PHP :
Option
Option
represents an optional value: every Option
is either
Option\Some
and contains a value, or Option\None
, and does not
Result
Result
is the type used for returning and propagating errors.
It has two variants, Ok(T)
, representing success and containing a value,
and Err(E)
, representing error and containing an error value.
Using those types makes it easier to handle result of operations correctly. Those two types are also carefully annotated to help static analysis tools discover potential issues such as invalid returned type or dead code.
composer req texthtml/maybe
Option
s
use TH\Maybe\Option;
/**
* @param Option<float>
*/
function divide(float $numerator, float $denominator): Option {
return match ($denomintor) {
0.0 => Option\none(),
_ => Option\some($numerator / $denominator)
};
}
// The return value of the function is an option
$result = divide(2.0, 3.0);
// Pattern match to retrieve the value
if ($result instanceof Option\Some) {
// The division was valid
echo "Result: {$option->unwrap()}");
} else {
// The division was invalid
echo "Cannot divide by 0";
}
Read more about Option
s
Result
s
use TH\Maybe\Option;
/**
* @param Result<int,string>
*/
function parse_version(string $header): Result {
return match ($header[0] ?? null) {
null => Result\err("invalid header length"),
"1" => Result\ok(1),
"2" => Result\ok(2),
default => Result\err("invalid version"),
};
}
$version = parse_version("1.x");
if ($version instanceof Result\Ok) {
echo "working with version: {$version->unwrap()}";
} else {
echo "error parsing header: {$version->unwrapErr()}";
}
// @prints working with version: 1
Read more about Result
s