Home >Backend Development >PHP Tutorial >Detailed explanation of examples of arrow functions in PHP

Detailed explanation of examples of arrow functions in PHP

coldplay.xixi
coldplay.xixiforward
2020-07-01 17:44:313524browse

Detailed explanation of examples of arrow functions in PHP

#Short closures called arrow functions are one of the long-awaited features that will be brought to version PHP7.4. It was proposed by Nikita Popov, Levi Morrison and Bob Weinand. You can read the original RFC here

Related learning recommendations:PHP Programming from Beginner to Master

Quick example taken from Doctrine DBAL

//老办法
$this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) {
    return in_array($v, $names);
});

// 使用箭头函数的新方法
$this->existingSchemaPaths = array_filter($paths, fn($v) => in_array($v, $names));

Let’s look at the rules

  1. fn is the key words instead of reserved function names.
  2. It can only have one expression, that is the return statement.
  3. No need to use the rereturn and use keywords.
  4. $this Variables, scopes and LSB scopes are automatically bound.
  5. You can type prompt parameters and return types.
  6. You can even use references& and the spread operator ...
##A few examples

//作用域示例
$discount = 5;
$items = array_map(fn($item) => $item - $discount, $items);

//类型提示
$users = array_map(fn(User $user): int => $user->id, $users);

//展开操作符
function complement(callable $f) {
    return fn(...$args) => !$f(...$args);
}

//嵌套
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;

//有效的函数签名
fn(array $x) => $x;
fn(): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;

Future Scope

    Multiline Arrow Functions
  1. Allows the use of arrow functions for functions within a class.
  2. //现今
    class Test {
        public function method() {
            $fn = fn() => var_dump($this);
            $fn(); // object(Test)#1 { ... }
    
            $fn = static fn() => var_dump($this);
            $fn(); // Error: Using $this when not in object context
        }
    }
    
    //也许在未来的某一天
    class Test {
        private $foo;
        private $bar;
    
        fn getFoo() => $this->foo;
        fn getBar() => $this->bar;
    }
My favorite points

    Callbacks can be shorter
  1. No need for the
  2. usekeyword to ask for variables.
Let me know what you think of these updates and what was your favorite takeaway?

Thanks for reading.

The above is the detailed content of Detailed explanation of examples of arrow functions in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete