我整理的PHP7.0主要新特性

王朝学院·作者佚名  2016-08-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

原文:http://php.net/manual/en/migration70.new-features.php

1.标量参数类型声明

现在支持字符串(string)、整型(int)、浮点数(float)、及布尔型(bool)参数声明,以前只支持类名、接口、数组及Callable

两种风格:强制转换模式(默认)与严格模式

<?php// Coercive modefunctionsumOfInts(int...$ints){returnarray_sum($ints);}var_dump(sumOfInts(2,'3',4.1));

2.返回类型声明

<?phpfunctionarraysSum(array...$arrays):array{returnarray_map(function(array$array): int {returnarray_sum($array);},$arrays);}PRint_r(arraysSum([1,2,3],[4,5,6],[7,8,9]));

3.??运算符

?? 用于替代需要isset的场合,这是一个语法糖。

<?php// Fetches the value of $_GET['user'] and returns 'nobody'// if it does not exist.$username=$_GET['user']??'nobody';// This is equivalent to:$username=isset($_GET['user'])?$_GET['user']:'nobody';// Coalescing can be chained: this will return the first// defined value out of $_GET['user'], $_POST['user'], and// 'nobody'.$username=$_GET['user']??$_POST['user']??'nobody';

4.<=> 比较运算符

就是看两个表达式值的大小,三种关系: = 返回0、< 返回-1、 > 返回 1

<?php// Integersecho1<=>1;// 0echo1<=>2;// -1echo2<=>1;// 1// Floatsecho1.5<=>1.5;// 0echo1.5<=>2.5;// -1echo2.5<=>1.5;// 1// Stringsecho"a"<=>"a";// 0echo"a"<=>"b";// -1echo"b"<=>"a";// 1

5.define支持定义数组类型的值

php 5.6已经支持CONST 语法定义数组类的常量,PHP7中支持define语法。

<?phpdefine('ANIMALS',['dog','cat','bird']);echoANIMALS[1];// outputs "cat"

6.匿名类

<?phpinterfaceLogger {publicfunctionlog(string$msg);}classapplication{private$logger;publicfunctiongetLogger(): Logger {return$this->logger;}publicfunctionsetLogger(Logger$logger){$this->logger =$logger;}

}$app=newApplication;$app->setLogger(newclassimplementsLogger {publicfunctionlog(string$msg){echo$msg;}

});var_dump($app->getLogger());

7.增加了整除函数 intdiv

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航