Оператор стрелочка в 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

Arrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions.

Arrow functions have the basic form fn (argument_list) => expr .

Arrow functions support the same features as anonymous functions, except that using variables from the parent scope is always automatic.

When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value. In the following example, the functions $fn1 and $fn2 behave the same way.

Example #1 Arrow functions capture variables by value automatically

$fn1 = fn ( $x ) => $x + $y ;
// equivalent to using $y by value:
$fn2 = function ( $x ) use ( $y ) return $x + $y ;
>;

The above example will output:

This also works if the arrow functions are nested:

Example #2 Arrow functions capture variables by value automatically, even when nested

$z = 1 ;
$fn = fn ( $x ) => fn ( $y ) => $x * $y + $z ;
// Outputs 51
var_export ( $fn ( 5 )( 10 ));
?>

Similarly to anonymous functions, the arrow function syntax allows arbitrary function signatures, including parameter and return types, default values, variadics, as well as by-reference passing and returning. All of the following are valid examples of arrow functions:

Example #3 Examples of arrow functions

fn (array $x ) => $x ;
static fn (): int => $x ;
fn ( $x = 42 ) => $x ;
fn (& $x ) => $x ;
fn &( $x ) => $x ;
fn ( $x , . $rest ) => $rest ;

Arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. A by-value binding means that it is not possible to modify any values from the outer scope. Anonymous functions can be used instead for by-ref bindings.

Example #4 Values from the outer scope cannot be modified by arrow functions

$x = 1 ;
$fn = fn () => $x ++; // Has no effect
$fn ();
var_export ( $x ); // Outputs 1

Changelog

Version Description
7.4.0 Arrow functions became available.

Notes

Note: It is possible to use func_num_args() , func_get_arg() , and func_get_args() from within an arrow function.

User Contributed Notes 5 notes

Unlike anonymous functions, arrow functions cannot have a void return type declaration.

May seem obvious, but if you thought you could make use of the benefits of arrow functions (using variables from the parent scope) to simplify a function or method call, keep in mind that this is only possible if you do NOT tell PHP that the arrow function does indeed return void.

In example 4 (Values from the outer scope cannot be modified by arrow functions)

$x = 1 ;
$fn = fn () => $x ++; // Has no effect
$fn ();
var_export ( $x ); // Outputs 1

?>

Here we can use reference variable in fn(&$x) and pass the value from function call $fn($x) so that we will get the output as expected with out using Anonymous functions.

$x = 1 ;
$fn = fn (& $x ) => $x ++;
$fn ( $x );
var_export ( $x );

But here it will not take values from parent scope automatically but we have to pass them explicitly.

As you already know, variable bindings occur in arrow functions by «by-value». That means, an arrow function returns a copy of the value of the variable used in it from the outer scope.

Now let us see an example of how a arrow function returns a reference instead of a copy of a value.

$fn = fn &(& $x ) => $x ; // Returns a reference

$y = & $fn ( $x ); // Now $y represents the reference

$y = 3 ; // Changing value of $y affects $x

Beware compact() not being able to access (import) variables from external scope (known in versions: 7.4.0, 7.4.8) (bug: https://bugs.php.net/bug.php?id=78970).

A workaround is available — use the variable directly; this will cause it to be imported into the arrow function’s namespace and make it available to the compact() too.

$aa = 111 ;
$accessing_variable_works = fn ( $bb ) => [ $aa , $bb ];
$compact_is_broken = fn ( $bb ) => compact ( ‘aa’ , ‘bb’ );
$compact_can_work_with_workaround = fn ( $bb ) => compact ( ‘aa’ , ‘bb’ ) + [ ‘workaround’ => $aa ];
var_dump ( $accessing_variable_works ( 333 ));
var_dump ( $compact_is_broken ( 555 ));
var_dump ( $compact_can_work_with_workaround ( 777 ));
?>

result:
array(2) [0]=>
int(111)
[1]=>
int(333)
>
PHP Notice: compact(): Undefined variable: aa in /home/m/vlt/guitar/tlb/s/public_html/index.php on line 9
array(1) [«bb»]=>
int(555)
>
array(3) [«aa»]=>
int(111)
[«bb»]=>
int(777)
[«workaround»]=>
int(111)
>

( fn ( $x ) => print( $x ))( 2 ); // Outputs 2

Источник

Стрелочные функции в 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 сменить формат даты
Оцените статью