在PHP中弃用每个函数的替代解决方案

问题描述 投票:0回答:1

我有一些遗留代码,使用每个代码返回菜单项值

function fetch () {

    $item = each( $this->menu );
    if ( $item ) {
        return ( $item['value'] );
    } else {
        reset ( $this->menu );
        return false;
    }
}

我试图通过添加一个模拟每个函数的函数来解决这个问题:

function each_replacement($arr) {
    $key = key($arr);
    $result = ($key === null) ? false : [$key, current($arr), 'key' => $key, 'value' => current($arr)];
    next($arr);
    return $result;
}

并将原始函数fetch更改为this(在另一个线程中找到它:

function fetch () {

    $item = this->each_replacement( $this->menu );
    if ( $item ) {
        return ( $item['value'] );
    } else {
        reset ( $this->menu );
        return false;
    }
}

但输出不正确,它只重复显示第一个菜单项并陷入无限循环,因此无法正常工作。

我的偏好只是重写代码并尝试了一些类似的东西

foreach ($this->menu as $item) {  }

代替

$item = each( $this->menu )

但这给了我这个错误:

Uncaught Error: Cannot use object of type MenuItem as array

如果有人能帮我提出一个很棒的解决方案。

完整的菜单代码在这里:http://sandbox.onlinephpfunctions.com/code/45a3c9c5c24232096744ecd9b915b13982ec551a

php each deprecated
1个回答
1
投票

关于代码:

  1. each() - 从数组中返回当前键和值对并使数组光标前进
  2. current() - 返回数组中的当前元素
  3. next() - 前进数组的内部指针

这意味着next()调用后跟每个()= current()val

~

注意:我会使用foreach,这只是解释如何保持fetch()函数。

码:

    /**
     * Iterates over the menu array
     * @return mixed item from menu
     * @access public
     */
    function fetch () {

        $item = current($this->menu);
        if ( $item ) {
            next($this->menu);
            return $item;
        }
        reset($this->menu);
        return false;

    }

测试here

© www.soinside.com 2019 - 2024. All rights reserved.