PHP code example of trehinos / thor-option

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

    

trehinos / thor-option example snippets


use Thor\Maybe\Option;
use Thor\Maybe\Maybe;

$myOption = Option::from("data...");
// Or
$myOption = Option::some("data...");

if ($myOption->isNone()) {
    // Never
}
// Or
if ($myOption->isA(Maybe::NONE)) {
    // Never
}

// Unwrap the optional value
if ($myOption->is() === Maybe::SOME) {
    // Here we know we can unwrap().
    $myString = $myOption->unwrap();
}

// Echoes the string if it is not none, or an empty string if it is :
echo $myOption->matches(
    fn(string $str) => $str,
    fn() => '',
);
// Or
echo $myOption->unwrapOr('');

use Thor\Maybe\Option;

$myOption = Option::from(null);
$myOption = Option::none();

$value = $myOption->unwrap(); // Throws a RuntimeException
$value = $myOption->unwrapOrThrow(new Exception("Custom Exception"));
$value = $myOption->unwrapOrElse(fn() => 'default value from callable');
$value = $myOption->unwrapOr('default value');

use Thor\Maybe\Option;
use Thor\Maybe\Maybe;

$myOption = Option::some("data...");

$myOption->matches(
    fn(string $str) => "My Option is Some($str)",
    fn() => 'My Option is None...',
);