PHP code example of hoa / option

1. Go to this page and download the library: Download hoa/option 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/ */

    

hoa / option example snippets


$x = Some(42);
$y = None();

assert($x->isSome());
assert($y->isNone());

assert(Some(42)->unwrap() === 42);
assert(None()->unwrap()); // will throw a `RuntimeException`.

$x = None();

assert($x->expect('Damn…') === 42);

$x = Some(42);
$y = None();

assert($x->unwrapOr(153) === 42);
assert($y->unwrapOr(153) === 153);

$x = Some(42);
$y = None();

$else = function (): int { return 153; };

assert($x->unwrapOrElse($else) === 42);
assert($y->unwrapOrElse($else) === 153);

$x = Some('Hello, World!');
$y = None();

assert($x->map('strlen') == Some(13));
assert($x->map('strlen') == None());

$x = None();

assert($x->mapOr('strlen', 0) == Some(0));

$x    = None();
$else = function (): int { return 0; };

assert($x->mapOrElse('strlen', $else) == Some(0));

assert(Some(42)->and(Some(153)) == Some(153));
assert(Some(42)->and(None())    == None());
assert(None()->and(Some(153))   == None());

$square = function (int $x): Option {
    return Some($x * $x);
};
$nop = function (): Option {
    return None();
};

assert(Some(2)->andThen($square)->andThen($square) == Some(16));
assert(Some(2)->andThen($nop)->andThen($square)    == None());

assert(Some(42)->or(Some(153)) == Some(42));
assert(None()->or(Some(153))   == Some(153));

$somebody = function (): Option {
    return Some('somebody');
};

assert(None()->orElse($somebody) == Some('somebody'));