1. Go to this page and download the library: Download php-fp/php-fp-either 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/ */
php-fp / php-fp-either example snippets
use PhpFp\Either\Constructor\{Left, Right};
$login = function ($username, $password)
{
if ($username != 'foo') {
return new Left(
'Invalid username'
);
}
if ($password != 'bar') {
return new Left(
'Incorrect password'
);
}
return new Right(['hello' => 'world']);
}
$prop = function ($k)
{
return function ($xs) use ($k)
{
return isset ($xs[$k])
? new Right($xs[$k])
: new Left('No such key.');
};
};
$id = function ($x)
{
return $x;
};
// Some examples...
$badUsername = $login('fur', 'bar')->chain($prop('id'));
$badPassword = $login('foo', 'bear')->chain($prop('id'));
$badKey = $login('foo', 'bar')->chain($prop('brian'));
$good = $login('foo', 'bar')->chain($prop('id'));
assert($badUsername->either($id, $id) === 'Invalid username');
assert($badPassword->either($id, $id) === 'Incorrect password');
assert($badKey->either($id, $id) === 'No such key.');
assert($good->either($id, $id) === 'world');
use PhpFp\Either\Either;
$id = function ($x) { return $x; };
assert(Either::of('test')->either($id, $id) == 'test');
use PhpFp\Either\Either;
use PhpFp\Either\Constructor\Left;
$either = Either::left('test');
assert($either instanceof Either);
assert($either instanceof Left);
use PhpFp\Either\Either;
use PhpFp\Either\Constructor\Right;
$either = Either::right('test');
assert($either instanceof Either);
assert($either instanceof Right);
use PhpFp\Either\Either;
$id = function ($x) { return $x; };
$f = function () { throw new \Exception; };
$g = function () { return 'hello'; };
assert(Either::tryCatch($f)->either($id, $id) instanceof \Exception);
assert(Either::tryCatch($g)->either($id, $id) === 'hello');
use PhpFp\Either\Constructor\{Left, Right};
$id = function ($x) { return $x; };
$addTwo = Either::of(
function ($x)
{
return $x + 2;
}
);
$a = new Right(5);
$b = new Left(4);
assert($addTwo->ap($a)->either($id , $id) === 7);
assert($addTwo->ap($b)->either($id, $id) === 4);