Download the PHP package yceruto/option-type without Composer
On this page you can find all versions of the php package yceruto/option-type. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download yceruto/option-type
More information about yceruto/option-type
Files in yceruto/option-type
Package option-type
Short Description An Option type that represents an optional value
License MIT
Informations about the package option-type
PHP Option type
The Option
type represents a value that might or might not be there. It's all about
null safety in PHP!
[!NOTE] Inspired by Rust's Option type and other languages like Scala, Swift, F#, etc.
Installation
Handling the presence or absence of a value with null
In PHP, denoting the absence of a value is done with null
, e.g. when a divide
function returns null
if the divisor is 0
.
Can you spot the issue in this code? Apparently, everything is fine until you try to
divide by zero. The function will return null
, and the success()
function will throw
a TypeError
because it expects an int
value, not null
.
The issue with this approach is that it's too easy to overlook checking if the value is
null
, leading to runtime errors, and this is where the Option
type comes in handy: it
always forces you to deal with the null
case.
Handling the presence or absence of a value with Option
Options often work with pattern matching to check if there’s a value and act accordingly,
always making sure to handle the null
case.
[!TIP] You can use the functions
some()
andnone()
as quick ways to create anOption
instance.some()
is just likenew Some()
, meaning it includes a value, whilenone()
is the same asnew None()
, indicating it is missing a value.
Documentation
- API Reference
- Examples
License
This software is published under the MIT License