Closures, Anonymous Function & High Order Functions in PHP

Saroj Subedi
2 min readSep 17, 2019

--

Photo by Yiran Ding on Unsplash

Closures are introduced in PHP 5.3. Functions which are created without any name (Anonymous Function) and Closures functions are used to represent these kind of functions.

A closure is good when we want a local function that’s only used for some small specific purposes.

Basically, Closure are the inner functions that have access to outer variables and used as a callback function to anonymous functions.

Simple Php Closure example

High Order function are related to functional programming. Basically these kind of functions has at least one of these features.

  • Takes one or more functions as arguments.
  • Return a function as its result.
Simple High Order Function example

Here are some inbuilt High Order Functions in PHP which will be more helpful to write clean and fast codes.

  • array_map
  • array_filter
  • array_reduce
  • array_walk

array_map : Applies the callback to the elements of the given arrays

array_filter : Filters elements of an array using a callback function

array_reduce: Iteratively reduce the array to a single value using a callback function

array_walk : Apply a user supplied function to every member of an array

PS; One more thing. lets try to use external variable inside high order function here : array_map

$add = 2;$lists = [1,2,3,4,5];array_map(function($value){
return $value + $add;
}, $lists);

We will get this error: Undefined variable: add

To solve this, we need to supply external variable to function using `use` keyboard.

--

--