# Functors in PHP Programming

Learn about functors as type classes and their properties using a calculator class coding example.

## We'll cover the following

For languages like PHP that don’t have default userland functor supportA type class that implements functor-compatible methods is an effective replacement for the functor concept. The **fantasyland** package helps with functor compliance checks. It’s a PHP port of a more complex JavaScript package of the same name. In addition to the required functor design, the **fantasyland** project also includes verification of laws that functors must satisfy.

## Functors are type classes

To effectively create a working functor, we need to implement the functor rubric—defined by category theory from the previous section—as a type class. A **type class** is a composite data type, which supports operator overloading. With a type class, it is possible to, with each invocation of a class method, overwrite its internal state and create a new immutable entity. Overriding in functors is expressed in the signatures of functions meant to be methods of the type class. Also referred to as ad-hoc polymorphism, operator overloading minimizes the redundancy of writing multiple methods to operationalize a new state. It truncates the boilerplate quite effectively.

Formally, a `T`

class with an `x`

parameter is a type class if the value of `x`

can be influenced by a set of operations (functions) that maintain its type constraints. Type classes are interfaces that influence behavior in Haskell, a language that promotes type usage.

The `Calculator`

class shown below is a simple demonstration of these ideas.

Get hands-on with 1200+ tech skills courses.