gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:03:37 24 4
gpt4 key购买 nike

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

<?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 的值,因此它每次都返回相同的值。要执行您想要的操作(没有函数参数),您需要一个匿名函数:
$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

关于php - 数组函数不使用 array_shift() 进行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64057356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com