PHP code example of petrknap / optional
1. Go to this page and download the library: Download petrknap/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/ */
petrknap / optional example snippets
namespace PetrKnap\Optional;
/** @var Optional<string> $optionalString */
$optionalString = Optional::of('data');
if ($optionalString->isPresent()) {
echo $optionalString->get();
}
OptionalResource::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void {
fwrite($tmpFile, 'data');
fclose($tmpFile);
});
namespace PetrKnap\Optional;
class YourClass {}
/**
* @extends OptionalObject<YourClass>
*/
class YourOptional extends OptionalObject {
protected static function getInstanceOf(): string {
return YourClass::class;
}
}
TypedOptional::register(YourOptional::class); // optional recommended step
function your_strong_typed_function(YourOptional $input): YourOptional {
return YourOptional::empty();
}
/**
* @param Optional<YourClass> $input
* @return Optional<YourClass>
*/
function your_weak_typed_function(Optional $input): Optional {
return YourOptional::empty();
}