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