Page MenuHomeDevCentral

Implement a similar datatype than Rust result
Changes PlannedPublic

Authored by dereckson on Sep 2 2018, 00:02.
Referenced Files
Unknown Object (File)
Sun, Jun 16, 17:47
Unknown Object (File)
Sun, Jun 16, 04:08
Unknown Object (File)
Tue, Jun 11, 01:49
Unknown Object (File)
Sun, Jun 9, 06:00
Unknown Object (File)
Fri, Jun 7, 11:58
Unknown Object (File)
Thu, Jun 6, 14:05
Unknown Object (File)
Wed, Jun 5, 10:13
Unknown Object (File)
Wed, Jun 5, 07:19



When a library needs to communicate an error status, to be handled
only by an initial caller down in the task or a success, the Result
generic type from the Rust library is convenient.

If PHP doesn't have the generics and Rust-like enum, we can at least
provide a base class Result, with two concrete implementations:

  • Err for exceptions
  • Ok for actual values


Test Plan

Implement in Zed story engine

Diff Detail

rKOT Keruald OmniTools
Lint Passed
Tests Passed
Result (branched from master)
Build Status
Buildable 2601
Build 2849: arc lint + arc unit

Event Timeline

dereckson created this revision.

Some ideas to make this code more useful:

  • a constructor to allow new Ok(42)
  • implement map methods:
    • or_else(defaultValue) -> return defaultValue for Err, $this->value for Ok
    • map() -> no op for Err, change value allowing type mutability for Value
    • map_err() -> no op for Value, change value allowing any Exception for Err

In PHP 8.1, could be interesting to do this:

Result sample use
use Keruald\OmniTools\DataTypes\Result;
use Keruald\OmniTools\DataTypes\ResultShape;

#[ResultShape(string, string)]
function doSomething() : Result {
    return ...;

$result = match (doSomething()) {
    $result->isOk() => $result->getValue(),
    default => throw new RuntimeException($result->getError()),

For this to work, we need two things:

  • Declare getError() in Result too
  • A ResultShape attribute to be able to typehint the Result