PHP code example of hopr / result

1. Go to this page and download the library: Download hopr/result library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hopr / result example snippets


$result = ok(5)
    ->map(fn($x) => $x * 2)        // Ok(10)
    ->map(fn($x) => $x + 1);       // Ok(11)

$cat_result = ok(['name' => 'Luna', 'age' => 7])
    // Bind `name` to the returned value of the callable
    ->use('name', fn($data) =>
        isset($data['name']) ? ok($data['name']) : err('Missing name'))
    // Bind `age` to the returned value of the callable. `name` is accessible here.
    ->use('age', fn($data, $name) =>
        isset($data['age']) ? ok($data['age']) : err('Missing age'))
    // And mapWith the previous `use` extracted fields!
    ->mapWith(fn($data, $name, $age) =>
        new Cat(name: $name, age: $age));

use function Hopr\Result\{ok, err};

// You can also use Ok::of(42);
$success = ok(42);
// You can also use Error::of("...");
$failure = err("something went wrong");

$result = ok(5)
    ->map(fn($x) => $x * 2)        // Ok(10)
    ->map(fn($x) => $x + 1);       // Ok(11)

$result = err("bad input")
    ->map(fn($x) => $x * 2)           // Still err("bad input")
    ->mapErr(fn($e) => "Error: $e");  // err("Error: bad input")

if ($result->isOk()) {
    $value = $result->unwrap();       // ✅ safe
} else {
    $value = $result->unwrapOr(0);    // fallback value
}

$parseNumber = function(string $input) {
    return is_numeric($input) 
        ? ok((int)$input)
        : err("Not a number");
};

$result = ok("42")->bind($parseNumber);  // Ok(42)