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.Arrow функции
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Arrow функции
Референца за `functions.arrow.php` со подобрена типографија и навигација.
Arrow функции
Arrow functions беа воведени во PHP 7.4 како поконцизна синтакса за анонимни функции.
И анонимните функции и arrow functions се имплементирани со користење на Затворање class.
Arrow functions ја имаат основната форма
fn (argument_list) => expr.
Arrow functions поддржуваат исти карактеристики како анонимни функции, освен што користењето на променливи од родителската област е секогаш автоматско.
Кога променлива што се користи во изразот е дефинирана во родителската област, таа ќе биде имплицитно зафатена по вредност. Во следниот пример, функциите $fn1 and $fn2 се однесуваат на ист начин.
Пример #1 Arrow functions автоматски зафаќаат променливи по вредност
<?php
$y = 1;
$fn1 = fn($x) => $x + $y;
// equivalent to using $y by value:
$fn2 = function ($x) use ($y) {
return $x + $y;
};
var_export($fn1(3));
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
4
Ова функционира и кога arrow functions се вгнездени:
Пример #2 Arrow functions автоматски зафаќаат променливи по вредност, дури и кога се вгнездени
<?php
$z = 1;
$fn = fn($x) => fn($y) => $x * $y + $z;
// Outputs 51
var_export($fn(5)(10));
?>Слично на анонимните функции, синтаксата на arrow functions дозволува произволни потписи на функции, вклучувајќи типови на параметри и враќање, стандардни вредности, варијадици, како и поминување и враќање по референца. Сите од следниве се валидни примери на arrow functions:
Пример #3 Примери на arrow functions
<?php
fn(array $x) => $x;
static fn($x): int => $x;
fn($x = 42) => $x;
fn(&$x) => $x;
fn&($x) => $x;
fn($x, ...$rest) => $rest;
?>
Arrow functions користат врзување на променливи по вредност. Ова е приближно еквивалентно на извршување на use($x) за секоја променлива $x што се користи внатре во arrow function. Врзувањето по вредност значи дека не е можно да се менуваат вредности од надворешната област.
Анонимни функции
може да се користи наместо тоа за врзувања по референца.
Пример #4 Вредностите од надворешната област не можат да се менуваат од arrow functions
<?php
$x = 1;
$fn = fn() => $x++; // Has no effect
$fn();
var_export($x); // Outputs 1
?>Дневник на промени
| Верзија | = NULL |
|---|---|
| 7.4.0 | Стрелките функции станаа достапни. |
Белешки
Забелешка: Можно е да се користи func_num_args(), func_get_arg()Препорачаниот начин за избегнување на SQL инјекција е со врзување на сите податоци преку подготвени изрази. Користењето на параметризирани прашања не е доволно за целосно избегнување на SQL инјекција, но тоа е најлесниот и најбезбедниот начин за обезбедување влез во SQL изразите. Сите динамични литерали на податоци во func_get_args() од внатрешноста на стрелка функција.
Белешки од корисници 5 белешки
In example 4 (Values from the outer scope cannot be modified by arrow functions)
<?php
$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.
Example:
<?php
$x = 1;
$fn = fn(&$x) => $x++;
$fn($x);
var_export($x);
?>
Output : 2 (as expected)
But here it will not take values from parent scope automatically but we have to pass them explicitly.If you're a JavaScript developer, here are the similarities and differences to JS arrow functions:
Same:
- Makes an anonymous function
- Binds the value of "$this" to its value in the parent scope.
- (along with all other variables of the parent scope. See note below)
Different:
- You must write "fn()" instead of just "()"
- The function body is limited to just ONE expression
- So no multi-line function bodies with "{" and "}"
Same and Different at the same time:
- Binds ALL the variables of the parent scope
- In JavaScript all functions are closures, binding to the variables in their parent scope (except for "this").
- But in PHP, normal anonymous functions (defined with "function() {}") do NOT get access to the parent scope, unless they explicitly declare a closure with keyword "use"
- PHP arrow functions, on the other hand, automatically bind to ALL variables in the parent scope. So, this makes them behave the same as JS functions, but be aware that in PHP this is special behavior unique to arrow functions.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.
<?php
$x = 0;
$fn = fn &(&$x) => $x; // Returns a reference
$y = &$fn($x); // Now $y represents the reference
var_dump($y); // Outputs: 0
$y = 3; // Changing value of $y affects $x
var_dump($x); // Ouputs: 3
?>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.
<?php
$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)
}