PHP code example of keerill / php-java-optional

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

    

keerill / php-java-optional example snippets


// ofEmpty refers Optional#empty() in java
// It is renamed as ofEmpty() because of empty() is reserved by PHP 
Optional::ofEmpty()
    ->isPresent(); // false

Optional::of('value')
    ->orElse('elseValue'); // value
 
Optional::ofEmpty()
    ->orElseThrow(fn () => new InvalidArgumentException()); // throws exception

Optional::ofEmpty()
    ->filter(fn ($a) => (int) $a); // function is not executed

Optional::of(5)
    ->map(fn ($a) => $a * 2)
    ->get(); // returns 10

Optional::ofEmpty()
    ->orElseGet(fn () => 10); // returns 10