Search code examples
phparrow-functions

How to write multiple expressions in PHP arrow functions


How do you write a PHP arrow function with multiple line expressions?

JavaScript one-liner example:

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

PHP one-liner 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 the PHP equivalent for multiple lines within an arrow function?


Solution

  • 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;
    }