PHP code example of ghostwriter / option

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

    

ghostwriter / option example snippets


use Ghostwriter\Option\Exception\NullPointerException;
use Ghostwriter\Option\None;
use Ghostwriter\Option\Some;
use Ghostwriter\Option\Option;

$message = '#BlackLivesMatter';
Option::new($message); // return `Some`

$some = Some::new($message); // return `Some`
echo $some->get(); // prints #BlackLivesMatter

$none = None::new(); // return `None`

// calling the `get` method on `None` will throw `NullPointerException`
echo $none->get(); // throw `NullPointerException`

echo $none->getOr('#BLM'); // prints #BLM

// calling the `new` static method with `null` will return `None`
Option::new(null); // return `None`

// calling the `new` static method with `null will throw `NullPointerException`
Some::new(null); // throws `NullPointerException`

// calling the `new` static method with `None will throw `NullPointerException`
Some::new(None::new()); // throws `NullPointerException`

--- Example

function divide(int $x, int $y): OptionInterface
{
    if ($y === 0) {
        return None::new();
    }

    return Some::new($x / $y);
}

divide(1, 0); // None
divide(1, 1); // Some(1)