Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple expressions in PHP arrow functions

How do you write PHP Arrow function with multiple line expressions?

JavaScript One Line Example:

const dob = (age) => 2021 - age;

PHP One Line Equivalent:

$dob = fn($age) => 2021 - $age;

Javascript Multiple Line Example:

const dob = (age) => {
   if(!age) return null;
   const new_age = 2021 - age; 
   console.log("Your new age is " + new_age);

   return new_age;
}

WHAT IS PHP Equivalent for multiple line????

like image 346
Emeka Mbah Avatar asked Jan 26 '21 15:01

Emeka Mbah


2 Answers

Arrow functions in PHP have the form fn (argument_list) => expr. You can only have a single expression in the body of the function.

You can write the expression over multiple lines without problem:

fn($age) =>
      $age
    ? 2021 - $age
    : null

If you really need multiple expressions, then you can simply use anonymous function. The closures aren't automatic as they are with arrow functions, but if you don't need it, it gives exactly the same result.

$dob = function ($age) {
    if (!$age) { return null; }
    $new_age = 2021 - ^$age; 
    echo "Your new age is ". $new_age;

    return $new_age;
}
like image 125
Blackhole Avatar answered Sep 24 '22 19:09

Blackhole


The usage of multiple expressions is not allowed, according to the RFC. It covers the assignment of only a single expression. The extension is discussed further down in the RFC, but not implemented

like image 20
Nico Haase Avatar answered Sep 21 '22 19:09

Nico Haase