PHPackages                             aphonix/result - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. aphonix/result

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

aphonix/result
==============

A zero-dependency, production-ready PHP implementation of Rust's Result type for elegant error handling.

v1.0.2(4mo ago)1198MITPHPPHP &gt;=7.1.0

Since Jan 7Pushed 4mo agoCompare

[ Source](https://github.com/aphonix/result)[ Packagist](https://packagist.org/packages/aphonix/result)[ RSS](/packages/aphonix-result/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (3)Versions (4)Used By (0)

Result for PHP
==============

[](#result-for-php)

A zero-dependency, production-ready PHP implementation of Rust's `Result` type. It brings elegant error handling and functional programming patterns to PHP 7.1+, eliminating the need for nested try-catch blocks and implicit exceptions.

🌟 Features
----------

[](#-features)

- **Rust-compliant API**: Method names and logic are 1:1 aligned with `std::result::Result`.
- **No `new` Keyword**: Functional constructors `Ok()` and `Err()` for a cleaner syntax.
- **Type Safe**: Encourages explicit error handling.
- **Chainable**: Supports monadic operations like `map`, `and_then`, and `or_else`.
- **PSR-12 Compliant**: Fully follows PHP coding standards.

---

🚀 Installation
--------------

[](#-installation)

Install the package via [Composer](https://getcomposer.org/):

```
composer require aphonix/result
```

---

🛠 Usage
-------

[](#-usage)

### Basic Example

[](#basic-example)

Instead of throwing exceptions that break the control flow, return a `Result`:

```
use function Ok;
use function Err;

function divide(float $numerator, float $denominator): \Aphonix\Result\Result {
    if ($denominator === 0.0) {
        return Err("Division by zero");
    }
    return Ok($numerator / $denominator);
}

$result = divide(10, 2);

if ($result->is_ok()) {
    echo "Success: " . $result->unwrap(); // 5
} else {
    echo "Error: " . $result->unwrap_err();
}
```

### Chaining Operations (The Rust Way)

[](#chaining-operations-the-rust-way)

Chain multiple fallible operations gracefully using `and_then` (monadic bind):

```
$final_value = fetch_user_data($id)           // Returns Result
    ->and_then('validate_user')               // Returns Result
    ->map(function($user) {                   // Transform value
        return $user->getName();
    })
    ->unwrap_or("Guest");                     // Default value if any step failed
```

---

📖 API Reference
---------------

[](#-api-reference)

### Variant Checks

[](#variant-checks)

- `is_ok()`: Returns `true` if the result is `Ok`.
- `is_err()`: Returns `true` if the result is `Err`.

### Value Extraction

[](#value-extraction)

- `unwrap()`: Returns the value or throws a `RuntimeException` (Panic).
- `unwrap_err()`: Returns the error or throws a `RuntimeException`.
- `expect(string $msg)`: Returns the value or throws with a custom message.
- `unwrap_or($default)`: Returns the value or the provided default.
- `unwrap_or_else(callable $op)`: Returns the value or computes a default from a closure.

### Transformation &amp; Chaining

[](#transformation--chaining)

- `map(callable $op)`: Transforms the `Ok` value.
- `map_err(callable $op)`: Transforms the `Err` value.
- `and_then(callable $op)`: Chains another operation that returns a `Result`.
- `or_else(callable $op)`: Recovers from an error by returning a new `Result`.

---

🧪 Testing
---------

[](#-testing)

The library is fully covered with unit tests. You can run them using PHPUnit:

```
./vendor/bin/phpunit tests
```

---

📜 License
---------

[](#-license)

The MIT License (MIT). Please see [License File](https://www.google.com/search?q=LICENSE) for more information.

---

🤝 Contributing
--------------

[](#-contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance76

Regular maintenance activity

Popularity12

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity32

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

131d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/a3c5ddbbccec951d0b2dd3cd66b2507dda9ae319b38eaf3720888efbdc09f4a7?d=identicon)[phonix](/maintainers/phonix)

---

Top Contributors

[![bqdove](https://avatars.githubusercontent.com/u/13446550?v=4)](https://github.com/bqdove "bqdove (1 commits)")

---

Tags

safeoptionresultfunctionalerror handlingmonadrust

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/aphonix-result/health.svg)

```
[![Health](https://phpackages.com/badges/aphonix-result/health.svg)](https://phpackages.com/packages/aphonix-result)
```

###  Alternatives

[spomky-labs/base64url

Base 64 URL Safe Encoding/Decoding PHP Library

15439.5M49](/packages/spomky-labs-base64url)[chippyash/monad

Functional programming Monad support

2828.1k8](/packages/chippyash-monad)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
