我整理的PHP 7.0主要新特性
截止到目前为止,PHP官方已经发布了php7的RC5版本,预计在11月份左右会发布第一个正式版本!现在来说php7的重大特性肯定已经是定型了,不会再有什么变动了。后续一些版本的迭代主要也就是修修bug,优化之类的。下面就来说话我们一直期待的php7.0新特征吧。
1.标量参数类型声明
现在支持字符串(string)、整型(int)、浮点数(float)、及布尔型(bool)参数声明,以前只支持类名、接口、数组及Callable
两种风格:强制转换模式(默认)与严格模式
<?php //Coercivemode functionsumOfInts(int...$ints) { returnarray_sum($ints); } var_dump(sumOfInts(2,'3',4.1));
2.返回类型声明
<?php functionarraysSum(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 //Fetchesthevalueof$_GET['user']andreturns'nobody' //ifitdoesnotexist. $username=$_GET['user']??'nobody'; //Thisisequivalentto: $username=isset($_GET['user'])?$_GET['user']:'nobody'; //Coalescingcanbechained:thiswillreturnthefirst //definedvalueoutof$_GET['user'],$_POST['user'],and //'nobody'. $username=$_GET['user']??$_POST['user']??'nobody';
4.<=>比较运算符
就是看两个表达式值的大小,三种关系:=返回0、<返回-1、>返回1
<?php //Integers echo1<=>1;//0 echo1<=>2;//-1 echo2<=>1;//1 //Floats echo1.5<=>1.5;//0 echo1.5<=>2.5;//-1 echo2.5<=>1.5;//1 //Strings echo"a"<=>"a";//0 echo"a"<=>"b";//-1 echo"b"<=>"a";//1
5.define支持定义数组类型的值
php5.6已经支持CONST语法定义数组类的常量,PHP7中支持define语法。
<?php define('ANIMALS',[ 'dog', 'cat', 'bird' ]); echoANIMALS[1];//outputs"cat"
6.匿名类
<?php interfaceLogger{ 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
小结:
PHP7在性能方面的突破成为近来最热门的话题之一,目前官方PHP7.0.0Beta2已经发布
新特性
性能提升:PHP7要比PHP5.6快两倍
全面一致的64位支持
移除了一些老的不在支持的SAPI(服务器端应用编程端口)和扩展
新增了空接合操作符(??)