A functor is a functional programming concept that has been adapted from a mathematical field called category theory.
In PHP, we can map a function to more than one value contained in the text by using a functor as a design pattern. Moreover, using a map on collections makes them a functor.
Any class that implements the given interface in it is called a functor.
<?php
interface Functor
{
public function fmap(callable $alpha): Functor;
}
?>
Let’s look at the given example, where we implement the functor interface in the Arr
class.
<?phpclass Arr implements Functor{protected $items;public function __construct(array $items){$this->items = $items;}public function fmap(callable $alpha): Functor{return new static(array_map($alpha, $this->items));}}$add2 = function ($array) { return $array + 1; };$arr = new Arr([1, 2, 3, 4]);$mappedArr =$arr->fmap($add2);print_r($mappedArr)?>
Arr
that implements the Functor
interface.$item
.Arr
class.fmap()
function of the Functor
interface.2
to each index of the Arr
.Arr
class.fmap()
function of Arr
and return the mapped array.Free Resources