数组函数不使用 array_shift() 进行迭代

Array function not iterating using array_shift()

下图,调用时的箭头函数,为什么我只得到第一个条目?

<?php

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = fn() => array_shift($stack);

var_dump($fruit());
var_dump($fruit());
var_dump($fruit());
var_dump($fruit());

给出:

string(6) "orange"
string(6) "orange"
string(6) "orange"
string(6) "orange"

https://3v4l.org/6sTm9

来自manual

A by-value binding means that it is not possible to modify any values from the outer scope

和:

Arrow functions capture variables by value automatically ... When a variable used in the expression is defined in the parent scope it will be implicitly captured by-value

因此您的函数无法修改 $stack 的值,因此它每次都 returns 相同的值。做你想做的事(没有函数参数)你需要一个匿名函数:

$fruit = function () use (&$stack) { return array_shift($stack); };

var_dump($fruit());
var_dump($fruit());
var_dump($fruit());
var_dump($fruit());

输出:

string(6) "orange"
string(6) "banana"
string(5) "apple"
string(9) "raspberry"

Demo on 3v4l.org

如果愿意传递参数,可以使用箭头函数:

$stack = array("orange", "banana", "apple", "raspberry");
$fruit = fn(&$s) => array_shift($s);

var_dump($fruit($stack));
var_dump($fruit($stack));
var_dump($fruit($stack));
var_dump($fruit($stack));

输出:

string(6) "orange"
string(6) "banana"
string(5) "apple"
string(9) "raspberry"

Demo on 3v4l.org