What are functors in PHP?

Overview

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.

Syntax

Any class that implements the given interface in it is called a functor.

<?php
interface Functor
{
   public function fmap(callable $alpha): Functor;
}
?>

Example

Let’s look at the given example, where we implement the functor interface in the Arr class.

<?php
class 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)
?>

Explanation

  • Lines 2–15: We define the class Arr that implements the Functor interface.
  • Line 4: We define the protected data member named $item.
  • Lines 6–9: We define the constructor of Arr class.
  • Lines 11–14: We define the fmap() function of the Functor interface.
  • Line 16: We define the anonymous function to add 2 to each index of the Arr.
  • Line 17: We create an object of the Arr class.
  • Line 18: We call the fmap() function of Arr and return the mapped array.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved