Skip to content

nspl\op

Ihor Burlachenko edited this page May 19, 2016 · 2 revisions

Class nspl\op provides functions that perform standard PHP operations and can be passed as callbacks to higher-order functions. Mimics Python's operator module. For example:

use const nspl\op\sum;
use function nspl\a\reduce;

assert(6 === reduce(sum, [1, 2, 3]));
Callbacks

The module provides the following operations both as functions and callbacks. See an example below.

Function Operation
sum +
sub -
mul *
div /
mod %
inc ++
dec --
neg -
band &
bxor ^
bor |
bnot ~
lshift <<
rshift >>
lt <
le <=
eq ==
idnt ===
ne !=
nidnt !==
ge >
gt >=
and_ &&
or_ ||
xor_ xor
not !
concat .
int (int)
bool (bool)
float (float)
str (string)
array_ (array)
object (object)
itemGetter($key)

Returns a function that returns key value for a given array

use function nspl\op\itemGetter;
use function nspl\a\map;

assert([2, 5, 8] === map(itemGetter(1), [[1, 2, 3], [4, 5, 6], [7, 8, 9]]));
propertyGetter($property)

Returns a function that returns property value for a given object

$userIds = map(propertyGetter('id'), $users);
methodCaller($method, array $args = array())

Returns a function that returns method result for a given object on predefined arguments

$userIds = map(methodCaller('getId'), $users);

Check more \nspl\op examples here.