Samuel Olaegbe
Samuel Olaegbe

Samuel Olaegbe

Using arrow functions in PHP 7.4

Using arrow functions in PHP 7.4

Samuel Olaegbe's photo
Samuel Olaegbe
·Mar 12, 2020·

min read

Subscribe to my newsletter and never miss my upcoming articles

Last November, PHP 7.4 was released and the entire community was so excited with the new features that this release brings with it. You can now build faster apps with PHP and also be excited while you work on them with these new release! See the full list of features

Now let's dig into what the arrow function is and how to use them in your PHP based projects. If you're a JavaScript developer, the following code snippet should look familiar to you:

users.forEach(user => console.log( )

This is a shorter version of what would have looked like this:

for(var x = 0; x <= users.length; x++){

With the above code we were using multiple lines for something that could have been done using a single line and we also had to use a loop construct and indexes and when you begin to do this all over your codebase it could become quite cumbersome and hard to read compared to a single line function.

A simple example in PHP would be:

   public function index(){

              return $post->author 


Now, the code above could be simplified as follows (in PHP 7.4):

      fn() => $post->author


It is important to note that the return keyword is not used in the arrow function, although it returns a value from the expression on the right hand side.

A simple way to think of it is this:

    $output = fn() => expression

The fn keyword is just a shorter way of writing function

By-value variable binding

The RFC for arrow functions in PHP 7.4 explains the use of by-value variable which basically binds a variable used in the closure such that it cannot be modified and any attempt to modify it will be silently ignored:

$x = "foo";

$output = fn() => $x . " bar"; // this is silently ignored


var_dump($x) //foo

Additional resources

And that is all about the arrow function in PHP 7.4. Please feel free to drop your comments, suggestions and questions!

Follow me on twitter @devloader

Share this


Blog by Samuel Olaegbe