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
  • 1
  • 2
  • 3
  • 4
  • 5

升級后版本:

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
  • 1
  • 2
  • 3
  • 4

升級完成之后發現有幾個框架在使用時都出現了問題,主要原因集中在7.2之后廢棄了一些功能,下面列出幾個常見的問題:

1、each函數已被廢棄:

之前版本寫法:

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

在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; }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

2、當傳遞一個無效參數時,count()函數將拋出warning警告:

之前版本寫法

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

在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; } }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

3、create_function被廢棄,可以用匿名函數來代替:

之前版本寫法:

<?php $newfunc = create_function('$a,$b', 'return "ln($a) + ln($b) = " . log($a * $b);'); echo "New anonymous function: $newfunc\n"; 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.
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在7.2版本中會有警告提示,可修改為匿名函數來替代:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM