Download the PHP package sassnowski/option without Composer
On this page you can find all versions of the php package sassnowski/option. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download sassnowski/option
More information about sassnowski/option
Files in sassnowski/option
Package option
Short Description A basic PHP implementation of the Option data type as found in Scala.
License MIT
Informations about the package option
Option Type for PHP
A PHP implementation of the Option
data type from Scala (or Maybe
from Haskell if you want).
DISCLAIMER: This package is not intented to be used in production. Its intend was to serve as a coding exercise to myself about how I would implement and Option Type in PHP. If you want to use this in production I'd recommend you use https://github.com/schmittjoh/php-option instead.
Installation
Install the package through composer:
That’s it! Now you can use it in your code.
Summary
An Option
represents an optional value, or in other words a value that may not exist. It is sometimes described as a List that contains a maximum of one item.
An Option
is used in places where otherwise null
might be used, e.g., the result of a Database Query. A more general way to put it is: A computation might return an Option
if it is not defined for some inputs.
Option::map($func)
Using Option
s means that a lot of code needs to be aware of this data type. In order to still be able to reuse functions that operate on unwrapped values, this class provides a map
function.
The purpose of the map
function is to lift a function that normally operators on regular values to now work on Option
values. Formally it turns a function of type
into a function of type
Example
The above example lifted the function length
of type string -> int
into a function of type Option string -> Option int
. This means that we can still write and use functions that were written without optional values in mind and simply lift them to a function that can handle Option
s.
An important characteristic of the map
method is, that the function that is being mapped over the option will never get executed if we’re dealing with an undefined value.
Option::flatMap($func)
Todo
Option::getOrElse($default)
Todo
Option::orElse($alternative)
Todo
Option::isDefined()
This function simply returns true
if the value is anything other than null
in which case it returns false
.
License
MIT