首页 > 解决方案 > 临时修复 php 8 中的 each() 函数(已解决)

问题描述

我正在更换服务器,我使用 php 8 从 centos 切换到 ubuntu 20.04。

我在服务器上的许多站点都使用这个旧类:https ://github.com/xmyl/Snoopy-2.0/blob/master/Snoopy.class.php

这些站点已经存在很长时间了,我使用这个类来访问我的附属程序的各种用户名和密码保护区域,读取 xml/rss/csv 文件,并自动处理它们。

问题是这个类经常使用 each() 函数,该函数以前被弃用,现在在 php 8 中被淘汰。

我现在需要更改服务器(这不是预期的),并让这个类以某种方式工作。之后我可以冷静地查看所有脚本,更新它们,修改它们等等,但现在我需要一个快速简单的解决方案来让它工作。

我尝试将 each() 更改为 current(),然后添加:

/**
 * Adds the depreciated each() function back into 7.2
 */
if (!function_exists('each')) {
    function each($arr) {
        $key = key($arr);
        $result = ($key === null) ? false : [$key, current($arr), 'key' => $key, 'value' => current($arr)];
        next($arr);
        return $result;
    }
}

它没有多大作用,脚本以:致命错误:允许的内存大小....

有一种快速简便的方法可以让它工作吗?(暂时)或者是一个和 snoopy 一样有效的快速替代方案?


只是为了关闭......在5秒内解决......解决方案......

if (!function_exists('each')) {
    function each(array &$array) {
        $value = current($array);
        $key = key($array);

        if (is_null($key)) {
            return false;
        }

        // Move pointer.
        next($array);

        return array(1 => $value, 'value' => $value, 0 => $key, 'key' => $key);
    }
}

https://gist.github.com/k-gun/30dd2bf8b22329a2dbc11a045aed3859

标签: phpeachphp-8

解决方案


您需要each()通过引用将数组传递给您的函数。当前写入数组的方式被复制到函数中,并且该副本的内部指针递增而不影响原始指针。

function each(&$arr) {
 /*...*/
}

推荐阅读