stiiv/php-optional

This package is not installable via Composer 1.x, please make sure you upgrade to Composer 2+. Read more about our Composer 1.x deprecation policy.

Handle PHP null values gracefully

dev-master 2018-05-29 13:28 UTC

This package is not auto-updated.

Last update: 2021-11-18 13:48:55 UTC


README

Handle PHP null values gracefully

Example:

source from (http://nitschinger.at/A-Journey-on-Avoiding-Nulls-in-PHP/)

<?php

include "vendor/autoload.php";

use Optional\Optional;

$possible = Optional::of(5);
var_dump($possible->isPresent()); // bool(true)
var_dump($possible->get()); // int(5)
var_dump($possible->getOrElse(99)); // int(5)
var_dump($possible->getOrNull()); // int(5)


$possible = Optional::of(null); // Throws 'NullPointerException' with message 'Unallowed null in reference found.'
$possible = Optional::fromNullable(null);
var_dump($possible->isPresent()); // bool(false)
var_dump($possible->get()); // Throws IllegalStateException
var_dump($possible->getOrElse(99)); // int(99)
var_dump($possible->getOrNull()); // NULL

$val1 = Optional::fromNullable(5);
$val2 = Optional::fromNullable(4);
$val3 = Optional::fromNullable(4);

var_dump($val1->equals($val2)); // bool(false)
var_dump($val2->equals($val3)); // bool(true)