Result

Represents either a success (ok) or a failure (error) result.

Overview

Normally, to represent a successful result, you'd just return it directly from a function or a method and to represent an error you'd use exceptions. However, exceptions are not ideal in cases where "an error is expected".

Instead of throwing exceptions, you can use Result::error() to represent recoverable errors and for successful results Result::ok(). The main insiprations are C++23 std::expected and Rust's Result.

API

static function ok(T $value = null): Result<T, E>

Returns a result with an ok value.

Result::ok(2);

static function error(E $value): Result<T, E>

Returns a result with an error value.

Result::error(3);

function isOk(): bool

Returns true if the result is ok.

assert(true === Result::ok(2)->isOk());
assert(false === Result::error(2)->isOk());

function equals(Result<T, E> $other): bool

Returns true if this result equals another result.

function map<U>(callable(T): U $fn): U

If the result has value, it maps its value using the provided $fn callback. Otherwise, returns the untouched result.

function mapError<U>(callable(E): U $fn): U

If the result has error, it maps its value using the provided $fn callback. Otherwise, returns the untouched result.

function valueOr<U>(U $value): T|U

Returns the contained value or the provided value on error.

Accessing the contained value and error

In case the Result has a value you can access it in two ways:

By deferencing (shorter)

And normally by calling its value which is equivalent to dereferencing:

If you try to reach for the contained value when is not present (the Result has an error) you'll get an exception:

To access an error:

And the same rules applies when accessing an error when is not present (the Result has a value).

Last updated