Что в php означает стрелка

PHP Arrow Functions

Summary: in this tutorial, you will learn about PHP arrow functions and how to use them effectively.

Introduction to PHP arrow functions

PHP 7.4 introduced the arrow functions that provide a more concise syntax for the anonymous functions.

The following illustrates the basic syntax for arrow functions:

fn (arguments) => expression;Code language: JavaScript (javascript)

In this syntax, an arrow function

The arrow function is functionally equivalent to the following anonymous function:

function(arguments) < return expression; >Code language: JavaScript (javascript)

Unlike anonymous functions, arrow functions can automatically access variables from their parent scopes.

PHP arrow function examples

Let’s take some examples of using arrow functions.

1) Assign an arrow function to a variable

The following example illustrates how to assign an arrow function to a variable:

 $eq = fn ($x, $y) => $x == $y; echo $eq(100, '100'); // 1 (or true) Code language: HTML, XML (xml)
  • First, define an arrow function and assign it to the $eq variable. The arrow function returns true if the two arguments are equal.
  • Second, call the arrow function via the $eq variable

2) Pass an arrow function to a function example

The following example shows how to pass an arrow function to the array_map() function:

 $list = [10, 20, 30]; $results = array_map( fn ($item) => $item * 2, $list ); print_r($results);Code language: HTML, XML (xml)
Array ( [0] => 20 [1] => 40 [2] => 60 )Code language: PHP (php)

In this example, the array_map() function applies the arrow function to every element of the $list array and returns a new array that includes the results.

3) Return an arrow function from a function

The following example illustrates how to return an arrow function from a function:

 function multiplier($x) < return fn ($y) => $x * $y; > $double = multiplier(2); echo $double(10); // 200Code language: HTML, XML (xml)
  • First, define a function called multiplier() that accepts an argument and returns an arrow function. Since the arrow function can access the variable from its parent scope, we can use the $x parameter inside the arrow function.
  • Second, call the multiplier() function and assign the returned value to the $double variable. The returned value of the multiplier() function is a function, therefore, we can call it via the $double variable.

Summary

  • An arrow function provides a shorter syntax for writing a short anonymous function.
  • An arrow function starts with the fn keyword and contains only one expression, which is the returned value of the function.
  • An arrow function have the access to the variables in its parent scope automatically.

Источник

Стрелочные функции в PHP 7.4

Стрелочные функции, также называемые короткими замыканиями (short closures), станут хорошим способом писать чистый код в PHP. Такая форма записи будет полезной при передаче замыканий в такие функции как array_map или array_filter .

// Коллекция объектов Post $posts = [/* … */]; $ids = array_map(fn($post) => $post->id, $posts);

Раньше нужно было писать так:

$ids = array_map(function ($post) < return $post->id; >, $posts);
  • Доступны с PHP 7.4
  • Начинаются с ключевого слова fn
  • Могут иметь только одно выражение, также являющееся возвращаемым значением
  • Не поддерживается return
  • Type-hintihg поддерживается в аргументах и возвращаемых значениях

Строготипизированный способ написания примера выше:

$ids = array_map(fn(Post $post): int => $post->id, $posts);
  • Поддерживается оператор переменного значения
  • Поддерживаются ссылки, как для аргументов, так и для возвращаемых значений

Если вы хотите вернуть значение по ссылке, используйте следующий синтаксис:

Стрелочные функции реализуют ту же функциональность, которую вы ожидаете от нормальных замыканий, только содержат в себе одно выражение.

Нет многострочности

Вы верно прочитали: короткие замыкания могут содержать только одно выражение. Это означает что вы не можете иметь несколько строк в них.

Аргументация такова: целью коротких замыканий является снижение многословности. fn , однозначно короче чем function во всех смыслах. Пропуск ключевых слов function и return ничего не меняет, но позволяет сделать код более читаемым.

Согласны ли вы с этим мнением? В то же время при наличии нового синтаксиса для однострочных функций, существует множество многострочных, которым тоже бы не помешал подобный апгрейд.

Надеюсь, в будущем, появится RFC с коротким объявлениим и многострочных функций, но пока это только мои мечты.

Переменные из внешней области видимости

Еще одним существенным различием между короткими и нормальными замыканиями является то, что первые не требуют использования ключевого слова use для получения доступа к данным из внешней области видимости.

$modifier = 5; array_map(fn($x) => $x * $modifier, $numbers);

Важно отметить, что вы не можете изменять эти переменные. Значения связаны по значению, а не по ссылке. Это означает, что вы можете изменять $modifier внутри короткого замыкания, но это не повлияет на переменную $modifier находящуюся вне.

Единственное исключение — ключевое слово $this , которое будет работать точно также, как и в нормальном варианте:

array_map(fn($x) => $x * $this->modifier, $numbers);

Будущие возможности

Я уже упоминал идею с многострочными короткими замыканиями выше. Еще одно полезное предложение — позволить использовать короткий синтаксис в классах, например для геттеров и сеттеров:

В целом, стрелочные функции это очень хорошая фича, хотя есть еще область для улучшения.

Есть ли у вас какие-либо мысли по этому поводу?

Источник

PHP RFC: Arrow Functions

This RFC is an alternative proposal to Bob Weinand’s Short Closures RFC which contains a lot of relevant information. This RFC will reference the short_closures RFC several times so readers should be familiar with it.

Introduction

Anonymous functions and closures can be verbose even though sometimes they are quite simple and contain only a single expression. Additionally, importing variables into the closure’s scope is manual and is painful overhead for single-expression closures. In practice these single-expression closures are common. This RFC proposes a more concise syntax for this pattern.

As an example of the declaration overhead, consider this function that I found online:

function array_values_from_keys($arr, $keys) { return array_map(function ($x) use ($arr) { return $arr[$x]; }, $keys); }

The closure performs a single operation $arr [ $x ] and is 8 characters but requires 30 other characters (excluding whitespace). This means that roughly 79% of the closure’s code is overhead (30/38). For this RFC these extra characters are called ‘boilerplate’. This RFC proposes arrow functions to reduce the amount of boilerplate by having a shorter syntax and importing used variables from the outer scope implicitly. Using arrow functions from this RFC this would reduce to the following:

This reduces the amount of boilerplate from 30 characters down to 8.

See more examples in the Examples section. The longer examples may be helpful to those struggling to understand why the RFC authors care about saving symbols and clarity on each closure.

Many other languages have ways to write closures in a succinct form as well. TODO: decide how much summary of this topic should be given here. At minimum provide links to closure documentation for a few other relevant and major languages?

Proposal

Arrow functions have the following form:

The expr is a single expression. This expression will be evaluated and then the result will be returned:

$mul2 = fn($x) => $x * 2; $mul2(3); // evaluates to 6

When a variable in the expression is defined in the parent scope it will be captured implicitly by-value. In the following example the functions identified by $versionA and $versionB are exactly equivalent:

$y = 1; $versionA = fn($x) => $x + $y; $versionB = function ($x) use ($y) { return $x + $y; };

Note that searching for variables to close over will descend into nested arrow functions and use sections of inline functions. This functionality is not expected to be common but is supported.

Arrow functions are similar to those found in EcmaScript 2015 (ES6) 1) and lambda expressions from C# 2) .

Type Declarations

This RFC does support type declarations for parameters and return types. This issue was noted multiple times on the mailing list during the short closures RFC as something that bothered voters. Therefore this RFC permits them but the authors discourage their general use in arrow functions.

Here are some examples to show the syntax:

References

Parameters and return values can be passed/returned by reference. As mentioned elsewhere, implicitly bound variables will be bound by value and not by reference. References go in the usual places:

Static Arrow Functions

The implementation currently supports static closures, for example static fn ( $x ) => static :: get ( $x ) . While supported it is uncertain whether it should be included in the final version. Having the implementation support it allows testers to determine usefulness and value.

Ambiguities

Arrow functions have no ambiguities, including array key definitions and yield expressions that provide a key. The fn prefix removes the ambiguities.

Backward Incompatible Changes

Unfortunately the fn keyword must be a full keyword and not just a reserved function name; this is to break the ambiguities with => for array and yield keys.

Ilija Tovilo analyzed the top 1,000 PHP repositories on GitHub to find usages of fn . The gist provides more information, but the rough findings are that all known existing usages of fn are in tests except one case where it is a namespace segment.

Patches and Tests

An implementation with tests can be found here: https://github.com/morrisonlevi/php-src/tree/arrow_functions. There are no known issues with it at this time; please build and test it.

Voting

Voting will be a simple Yes/No that requires 2/3 or more of the votes to be “Yes” to be accepted.

Examples

$extended = function ($c) use ($callable, $factory) { return $callable($factory($c), $c); }; // with arrow function: $extended = fn($c) => $callable($factory($c), $c);

This reduces the amount of boilerplate from 44 characters down to 8.

$this->existingSchemaPaths = array_filter($paths, function ($v) use ($names) { return in_array($v, $names); }); // with arrow function $this->existingSchemaPaths = array_filter($paths, fn($v) => in_array($v, $names));

This reduces the amount of boilerplate from 31 characters down to 8.

The complement function as found in many libraries:

function complement(callable $f) { return function (. $args) use ($f) { return !$f(. $args); }; } // with arrow function: function complement(callable $f) { return fn(. $args) => !$f(. $args); }

The following example was given to me by tpunt:

$result = Collection::from([1, 2]) ->map(function ($v) { return $v * 2; }) ->reduce(function ($tmp, $v) { return $tmp + $v; }, 0); echo $result; //6 // with arrow functions: $result = Collection::from([1, 2]) ->map(fn($v) => $v * 2) ->reduce(fn($tmp, $v) => $tmp + $v, 0); echo $result; //6

Future Scope: Multi-Statement Bodies

Some languages permit multi-statement closures with a syntax like:

(parameter_list) => { stmt1; stmt2; //… }

In this case nothing would be automatically returned. This feature was included in the short closures RFC but there were two primary complaints about it:

If you are specifying multiple statements doesn’t that work against the purpose of being concise and short?

This RFC omitted this feature for these reasons. If arrow functions are accepted and become more common it may make sense to revisit this feature.

Источник

Читайте также:  Curl php для чайников
Оцените статью