Download the PHP package aphonix/option without Composer
On this page you can find all versions of the php package aphonix/option. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package option
๐ฆ Rust-style Option for PHP ๐
A lightweight, zero-dependency implementation of Rust's Option
โจ Features
- PHP 7.1+ Compatibility: Fully supports all versions from PHP 7.1 up to PHP 8.4+.
- Strict Rust API: Ported core methods from the Rust Standard Library (std::option).
- Singleton None: Memory-efficient implementation using a singleton for the None type.
- Global Helper Functions: Idiomatic Some() and None() functions for a clean development experience.
- Explicit Optional Values: Encourages callers to handle values that may be absent instead of relying on implicit null checks.
๐ Installation
You can install the package via Composer:
๐ Quick Start
Basic Usage
Some(null) is allowed and represents a present value whose payload is null. Use None() when the value is absent.
Functional Chaining
Avoid defensive is_null() nesting with monad-style chaining:
Advanced: and_then (FlatMap)
Use and_then when your transformation closure returns an Option itself:
๐ API Reference
Check Methods
| Method | Description |
|---|---|
is_some(): bool |
Returns true if the option is a Some value. |
is_none(): bool |
Returns true if the option is a None value. |
is_some_and(callable $f): bool |
Returns true if the option is Some and the value inside matches the predicate. |
Unwrapping Methods
| Method | Description |
|---|---|
| unwrap() | Returns the inner value. Throws an Exception (Panic) if the value is None. |
| expect(string $msg) | Returns the inner value. Throws an Exception with a custom message if the value is None. |
unwrap_or($default) |
Returns the inner value if it exists, otherwise returns the provided default. |
unwrap_or_else(callable $f) |
Returns the inner value if it exists, otherwise returns the result of the closure. |
Transformation & Filtering
| Method | Description |
|---|---|
map(callable $f): Option |
Maps an Option |
map_or($default, callable $f) |
Returns the provided default result, or applies a function to the contained value. |
filter(callable $f): Option |
Returns None if the option is Some and the closure returns false. |
and_then(callable $f): Option |
Returns None if the option is None, otherwise calls the closure with the value and returns the result. |
Logical Operations
| Method | Description |
|---|---|
and(Option $optB): Option |
Returns None if the option is None, otherwise returns $optB. |
or(Option $optB): Option |
Returns the option if it contains a value, otherwise returns $optB. |
xor(Option $optB): Option |
Returns Some if exactly one of self, $optB is Some, otherwise returns None. |
๐งช Testing
This project uses PHPUnit to verify the core behavior:
๐ License
The MIT License (MIT). Please see the License File for more information.