PHP code example of emilianobovetti / php-option

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

    

emilianobovetti / php-option example snippets


// import library
use EmilianoBovetti\PhpOption\Option;
// if you need direct access to Some class
use EmilianoBovetti\PhpOption\Some;

// $user object contains a reference to addres
// which contains a reference to city,
// but the user, the address and the city
// can be null
$city = isset($user->address->city) ? $user->address->city : 'Unknown';

// this line makes the same thing
$city = Option::create($user)->address->city->getOrElse('Unknown');

// we can change this
if (isset($user->address->city)) {
    $city = $user->address->city;
    $result = $city === 'rome' ? 'home' : $city;
} else {
    $result = 'city unknown';
}

// with a little more compact solution
$result = Option::create($user)->address->city
    ->map(function ($city) { return $city === 'rome' ? 'home' : $city; })
    ->getOrElse('city unknown');

// no problem, objects and arrays are treated identically
$user = [ 'defined' => [ 'key' => 0 ] ];

$key = Option::create($user)->defined->key->get(); // $key is 0

$user = null;

$key = Option::create($user)->undefined->key->getOrElse(0); // $key is 0 again

// use callbacks for lazy-evaluation
Option::create($user)->some->property
    ->orElse(function () { return $this->heavyLoad(); })
    ->orElse(function () { return $this->someFallback(); })
    ->getOrElse(function () { return $this->lastChance(); });

echo Option::create($user)->address->city->name; // will print city name or empty string

$array = [ 'defined' => [ 'key' => 0 ] ];
isset(Option::create($array)->defined->key); // true

isset(Option::create(null)->undefined->key); // false

$option = Option::create(0);
$option(1); // 0
$option();  // 0

$option = Option::none();
$option(1); // 1
$option();  // NoneValueException
bash
git clone [email protected]:emilianobovetti/php-option.git
cd php-option
composer install
./vendor/bin/phpunit