Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

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????

question from:https://stackoverflow.com/questions/65903832/how-to-write-multiple-expressions-in-php-arrow-functions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...