PHP code example of yceruto / option-type

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

    

yceruto / option-type example snippets


function divide(int $dividend, int $divisor): ?int
{
    if (0 === $divisor) {
        return null;
    }

    return intdiv($dividend, $divisor);
}

function success(int $result): string {
    return sprintf('Result: %d', $result);
}

$result = divide(10, 2);

echo success($result);

use Std\Type\Option;
use function Std\Type\Option\none;
use function Std\Type\Option\some;

/**
 * @return Option<int>
 */
function divide(int $dividend, int $divisor): Option
{
    if (0 === $divisor) {
        return none();
    }

    return some(intdiv($dividend, $divisor));
}

function success(int $result): string {
    return sprintf('Result: %d', $result);
}

// The return value of the function is an Option
$result = divide(10, 2);

// Pattern match to retrieve the value
echo $result->match(
    // The division was valid
    some: fn (int $v) => success($v),
    // The division was invalid
    none: fn () => 'Division by zero!',
);