Anonymous Function VS Closure

Pramod Khatiwada
1 min readFeb 26, 2021

Anonymous Function

An anonymous function is a function that does not have a name. Like the classic way we create the function definition with the name and call it in multiple places. But in the Anonymous function, we do not need to name it. It is really efficient if we do not need that function multiple times.

function (arg1, arg2) => {
// do something
}

Or we can assign an anonymous function to the variable. Now we can reference the function with the variable. We can pass a function as an argument and return the function as the return value. In PHP To run the function dynamically we can use call_user_fun(‘funcname’).

Closure

The closure is something that is similar to the anonymous function but closure has access to the one level up scope from where it is running. That means it has access to the variable outside of this scope. JavaScript has wonderful closure support.

PHP also we have support for closure but have to use ‘use’ keyword to pass variable access inside the closure.

function myfunction ($min) {
return function ($item) use ($min) {
return $item->$min
}
}

Here we have used the use keyword to pass $min variable inside the scope of the closure.

--

--

Pramod Khatiwada

Pondering thoughts, questioning them, and trying to solve the mystery of life.