如何解决每个PHP这个不推荐使用的功能 [英] How to resolve this deprecated function each php

查看:65
本文介绍了如何解决每个PHP这个不推荐使用的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP 7.2中,不推荐使用each. 文档说:

With PHP 7.2, each is deprecated. The documentation says:

警告该功能自PHP 7.2.0起已被弃用.强烈建议不要使用此功能.

Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

如何更新代码以避免使用它?以下是一些示例:

How can I update my code to avoid using it? Here are some examples:

$ar = $o->me;
reset($ar);
list($typ, $val) = each($ar);

  • $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = each($out);
    

  • for(reset($broken);$kv = each($broken);) {...}
    

  • list(, $this->result) = each($this->cache_data);
    

  • // iterating to the end of an array or a limit > the length of the array
    $i = 0;
    reset($array);
    while( (list($id, $item) = each($array)) || $i < 30 ) {
        // code
        $i++;
    }
    

  • 推荐答案

    在前两个示例中,可以使用key()current()分配所需的值.

    For your first two example cases, you could use key() and current() to assign the values you need.

    $ar = $o->me;   // reset isn't necessary, since you just created the array
    $typ = key($ar);
    $val = current($ar);
    

  • $out = array('me' => array(), 'mytype' => 2, '_php_class' => null);
    $expected = [key($out), current($out)];
    

  • 在这种情况下,您可以使用next()后移光标,但是如果其余代码不依赖于此,则没有必要.

    In those cases, you can use next() to advance the cursor afterward, but it may not be necessary if the rest of your code doesn't depend on that.

    1. 对于第三种情况,我建议只使用foreach()循环,然后在循环内分配$kv.
    1. For the third case, I'd suggest just using a foreach() loop instead and assigning $kv inside the loop.

        foreach ($broken as $k => $v) {
            $kv = [$k, $v];
        }
    

    1. 对于第四种情况,键似乎在list()中被忽略,因此您可以分配当前值.
    1. For the fourth case, it looks like the key is disregarded in list(), so you can assign the current value.

        $this->result = current($this->cache_data);
    

    与前两种情况一样,可能有必要使用next()来移动光标,具体取决于其余代码与$this->cache_data交互的方式.

    Like the first two cases, it may be necessary to advance the cursor with next() depending on how the rest of your code interacts with $this->cache_data.

    1. 第五个可以替换为for()循环.

        reset($array);
        for ($i = 0; $i < 30; $i++) {
            $id = key($array);
            $item = current($array);
            // code
            next($array);
        }
    

    这篇关于如何解决每个PHP这个不推荐使用的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆