Anonymous and Arrow Functions in PHP

I’ve already covered the basics of functions in PHP in one of a previous tutorials. Even though PHP has a lot of built-in functions, it gives us the choice to define our own functions as well. There are different ways to define our own functions in PHP.

This tutorial will teach you about the features and uses of anonymous functions in PHP. You’ll also learn about the newer arrow function syntax in PHP.

Anonymous Functions in PHP

Whenever we define a function in PHP, we usually provide a name for it as well. This name is used to call the function at a later time whenever we need it. However, a function is sometimes required only at one place and nowhere else. Let’s say you are working on a big project that requires you to write about 50 or more such functions.

In such cases, it is much more easier to just place the function definition where it is needed without worrying about coming up with a name for the function. These types of functions are called anonymous functions. They are particularly helpful when you are dealing with functions that are only four to five lines long.

Implementing Callbacks With Anonymous Functions

One of the most common uses of anonymous functions is as callbacks. Callback functions are called by the main function to do some task based on logic you supply. We can use both built-in and user defined functions as callbacks. Here is an example of such functions:

In the code above, we simply return multiples of five from a given array of numbers. The second parameter to array_filter() is our callback function. As you can see, it performs a trivial task of just checking if number is divisible by five. Without anonymous functions, we would have to define this function somewhere else and come up with a non-colliding name.

Assigning Anonymous Functions to Variables

We usually assign a name to any function that we define in PHP. This name is used to call the function later whenever it is needed. However, anonymous functions don’t have any name. This can make it difficult for us to call them later if need arises.

One nice feature of anonymous functions is that we can assign them to variables or store them inside numerical or associative arrays. After that, we can just call these functions using the variable name. Here is an example:

As you can see in the above code, these anonymous functions can be assigned to variables and called just like regular functions.

Anonymous Functions can Inherit Variables From Parent Scope

In one of our previous articles called Understanding Variable Scope in PHP, we covered variable scope in detail. Basically, PHP has a global scope and a function level scope. You cannot access variables defined somewhere else inside your functions. Similarly, variables defined inside a function won’t be accessible outside it.

One way to access outside variables inside a function is to use the global keyword. However, this approach has some disadvantages as it can make code maintenance harder in the long term.

PHP also has a special use keyword that allows you to access variables from parent scope inside an anonymous function. Lets understand the difference between global and use with some examples:

In the above example, we have defined the variables $pad and $full_length two times. They are part of the global scope when defined at the top. We define those two variables again inside function parent_function(). However, they are not related to variables defined in the global scope because functions have their own scope in PHP.

When we use these variables inside our padding() function with the help of global keyword, we are actually accessing the global values. This is apparent from the output of parent_function(). We were also able to change the value of global $full_length inside our function.

We can rewrite the above code to use anonymous functions and the use keyword. It will look like the snippet below:

This time, we made our padding function anonymous and accessed $pad and $full_length with the help of use keyword. The value of these variables was taken from the parent scope. Removing the variables from the parent scope will give you errors about undefined variables.

Also note that the anonymous function is actually working with the copies of variables in parent scope. That’s why the value of $full_length did not change outside the anonymous function.

You can pass these variables by reference if you want those changes to be reflected outside the function.

Making Anonymous Callback Functions More Versatile

In the beginning of this tutorial, we learned that anonymous functions are commonly used as callbacks. This was demonstrated using the array_filter() function. In that example, we filtered out all the numbers in our array that were not a multiple of 5. This 5 was hard-coded into the callback function.

What if we wanted to make our filter function more versatile so that it can filter out the numbers that are not multiple of some other values like 8 or 10? One way to do that would be to pass the other number as a second parameter.

Unfortunately, the callback function expects a specific number (one in this case) of parameters. Therefore, passing two parameters causes an error. We can get around this limitation with the help of the use keyword. As we saw in the previous section, anonymous functions can inherit variables from parent scope with use keyword. Here is a modified version of our callback based on this fact.

We create an array of bunch of factors whose multiples we want to filter. After that, we use a foreach loop to iterate through the factors. Each factor is passed to the callback function for array_filter() giving us multiples for all of them.

Arrow Functions in PHP

Arrow functions are basically a shorter way of writing simple anonymous functions. They were introduced in PHP 7.4. The keyword function is replaced with fn and the return keyword is completely omitted when defining arrow functions. They only contain one expression and that expression is the return value of the arrow function.

One more feature of arrow functions is that variables defined in the parent scope are implicitly available to them without adding the use keyword.

Running this code outputs the same values as the previous code snippet. As I mentioned earlier, the variable $factor becomes available to our arrow function without adding the use keyword.

Final Thoughts

In this tutorial, we covered some features and uses of anonymous functions in PHP. This includes things like using them for callbacks or assigning them to variables to call them later. We also learned how we can access the variables defined in parent scope inside the anonymous functions. Later, we used this feature to created more useful callback functions.

We also learned that simple anonymous functions can be written in a more concise manner by using the arrow function syntax.