PHP code example of sassnowski / option

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

    

sassnowski / option example snippets


function divide($a, $b)
{
	if (0 === $b)
	{
		return Option::None();
	}
	
	return new Option($a / $b);
}

$result = divide(10, 5);
$result->get(); // 2

$result2 = divide(10, 0);
$result->isDefined(); // false

// Note: This example uses PHP 7 type hinting. This is in no 
// way necessary for this package to work and is simply there 
// to illustrate the types that these functions are supposed to
// operate on.

function length(string $a): int
{
	return strlen($a);
}

$length1 = (new Option("abc"))->map('length');
$length1->isDefined(); // true
$length1->get(); // 3

// The length function never gets executed, since we're 
// dealing with an undefined value.
$length2 = Option::None->map('length');
$length2->isDefined(); // false
$length2->get(); // RuntimeException