站长资讯网
最全最丰富的资讯网站

总结PHP升级7.2之后需要注意的事情

总结PHP升级7.2之后需要注意的事情

最近升级了PHP版本,从7.1升级到7.2,升级前版本:

PHP 7.1.14 (cli) (built: Feb 2 2018 08:42:59) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.1.14, Copyright (c) 1999-2018, by Zend Technologies with Xdebug v2.6.0, Copyright (c) 2002-2018, by Derick Rethans

升级后版本:

PHP 7.2.2 (cli) (built: Feb 24 2018 17:51:12) ( ZTS DEBUG ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.2.2, Copyright (c) 1999-2018, by Zend Technologies

推荐(免费):PHP7

升级完成之后发现有几个框架在使用时都出现了问题,主要原因集中在7.2之后废弃了一些功能,下面列出几个常见的问题:

1、each函数已被废弃:

之前版本写法:

<?php     $array = array();     each($array);      // Deprecated:  The each() function is deprecated. This message will be suppressed on further calls

在7.2版本中会提示过时,可以使用foreach替代each方法,也可以自己修改each方法替代:

<?php     function func_new_each(&$array){        $res = array();       $key = key($array);       if($key !== null){            next($array);             $res[1] = $res['value'] = $array[$key];           $res[0] = $res['key'] = $key;        }else{           $res = false;        }       return $res;     }

2、当传递一个无效参数时,count()函数将抛出warning警告:

之前版本写法

<?php     count('');    // Warning:  count(): Parameter must be an array or an object that implements Countable

在7.2版本中将严格执行类型区分,参数类型不正确,将会出现警告,所以需要在使用count方法时注意参数的值,不过也可以通过自己修改方法来替代(不建议):

<?php     function func_new_count($array_or_countable,$mode = COUNT_NORMAL){         if(is_array($array_or_countable) || is_object($array_or_countable)){            return count($array_or_countable, $mode);         }else{            return 0;         }     }

3、create_function被废弃,可以用匿名函数来代替:

之前版本写法:

<?php     $newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);');    echo "New anonymous function: $newfuncn";    echo $newfunc(2, M_E) . "n";    // outputs     // New anonymous function: lambda_1     // ln(2) + ln(2.718281828459) = 1.6931471805599      // Warning This function has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

在7.2版本中会有警告提示,可修改为匿名函数来替代:

<?php     $newfunc = function ($a,$b){         return "ln($a) + ln($b) = " . log($a * $b);     };    echo $newfunc(2, M_E) . "n";

赞(0)
分享到: 更多 (0)