A container object which may or may not contain a non-null value. If a value is present,
isPresent()will returntrueandget()will return the value.Additional methods that depend on the presence or absence of a contained value are provided, such as
orElse()(return a default value if value not present) andifPresent()(execute a block of code if the value is present).This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
It is an easy way to make sure that everyone has to check if they have (not) received a null.
use PetrKnap\Optional\Optional;
$stringOption = Optional::of('data');
if ($stringOption->isPresent()) {
echo $stringOption->get();
}
Optional::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void {
fwrite($tmpFile, 'data');
fclose($tmpFile);
}, else: fn () => print('tmpfile() failed'));This library provides OptionalOverrides trait to help you implement your own wrapper with full static analysis support (see Some\Optional class):
use PetrKnap\Optional\Optional;
use PetrKnap\Optional\OptionalOverrides;
/**
* @template-covariant T of mixed type of non-null value
*
* @extends Optional<T>
*/
final class MyOptional extends Optional
{
/** @use OptionalOverrides<T> */
use OptionalOverrides;
}The equals() method has been refactored to align strictly with Optional specification.
- Comparing two empty
Optionals now evaluates totrue. Comparing any two emptyOptionalinstances evaluates totrue, regardless of their underlying type.Optional<String> emptyOptStr = Optional.empty(); Optional<Array> emptyOptArr = Optional.empty(); emptyOptStr.equals(emptyOptArr); // true
- Comparing an
Optionalagainst a raw value now evaluates tofalse. Passing non-optional values directly intoequals()will immediately evaluate tofalse.Optional.of("").equals(""); // false
Run composer require petrknap/optional to install it.
You can support this project via donation.
The project is licensed under the terms of the LGPL-3.0-or-later.