PHP

PHP BOOTCAMP: Closures Demystified


Yo DAWG, Here is a function for your function.

If you have worked with Javascript a lot, you would have used functions inside functions several times. I mean anonymous functions ( functions without a name, I call them bastard functions ). I also mean inner functions that possess the ability to access properties within the scope of the outer functions.

In PHP, Closures exist and it’s as powerful as the name sounds. Wait,..Holup!, Holup!..Are you currently thinking this is Clojure. Nah, Please do me a favour, it is Closure!. Clojure is just another programming language and I have a colleague of mine that blabs about it all day, Damn!!!

Come, let’s take the first step, We can assign a nameless function to a variable like so:

Then, we can call the function like so:

So, our result would be:

Awesome!

This is an anonymous function, but PHP developers loosely call them lambdas and Closures.

Now, there is actually a distinction. An ordinary standalone anonymous function is a Lambda.

A Closure is an anonymous function that can exist inside another function and have the ability to access the properties and parameters of the outer function.

There is also an inbuilt Class called Closure.

Now, Let’s see why we really need Closures if you may ask!

The ability to pass functions into other functions is what makes Closures dope!. There are several situations where you’ll want to pass several tiny bits of sweet logic into a function and as long as you are using PHP 5, I mean PHP >= 5.3 version,..then you are safe to use it in your application.

Let’s see a cool example of that.

For the getResponse function, I passed in two type-hinted parameters…an array and a closure.

Type-hint is basically specifying the type of a parameter passed into a function. It’s to protect anyone from just passing any type of value into a function. 

Now, let’s write a closure.

Another One:

Now we have $toJson Closure and $flipResult Closure.

Let’s use them with our getResponse function.

Our results would look like this:

That’s how easy it is to use Closures :smile:

Please, if you have any questions or observations, Let me know in the comments section.