相思资源网 Design By www.200059.com

一、可空类型

可空类型主要用于参数类型声明和函数返回值声明。

主要的两种形式如下:

<"htmlcode">
<"htmlcode">
<"color: #ff0000">二、list 的方括号简写

我们知道在 PHP5.4 之前只能通过 array() 来定义数组,5.4之后添加了 [] 的简化写法(省略了5个字符还是很实在的)。

<"a" => 1, "b" => 2, "c" => 3);

// 5.4 及之后
$array = [1, 2, 3];
$array = ["a" => 1, "b" => 2, "c" => 3];

引申到另外一个问题上,如果我们要把数组的值赋值给不同的变量,可以通过 list 来实现:

<"htmlcode">
<"htmlcode">
<"a" => $a, "b" => $b, "c" => $c] = $array;

PHP7.1 实现了这个特性。但是要注意的是:出现在左值中的 [] 并不是数组的简写,是 list() 的简写。

但是并不仅仅如此,新的 list() 的实现并不仅仅可以出现在左值中,也能在 foreach 循环中使用:

<"x" => $x, "y" => $y]) {
 var_dump($x, $y);
}

不过因为实现的问题,list() 和 [] 不能相互嵌套使用:

<"color: #ff0000">三、允许在 list 中指定 key

上文提到过,新的 list() 的实现中可以指定key:

<"a" => 1, "b" => 2, "c" => 3];
["a" => $a, "b" => $b, "c" => $c] = $array;

这也就相当于:

<"htmlcode">
<"htmlcode">
<"htmlcode">
<"key" => $keyed) = $array;

更复杂的情况,list 也支持复合形式的解析:

<"x" => 1, "y" => 2],
 ["x" => 2, "y" => 1]
];

list(list("x" => $x1, "y" => $y1), list("x" => $x2, "y" => $y2)) = $points;

$points = [
 "first" => [1, 2],
 "second" => [2, 1]
];

list("first" => list($x1, $y1), "second" => list($x2, $y2)) = $points;

以及循环中使用:

<"x" => 1, "y" => 2],
 ["x" => 2, "y" => 1]
];

foreach ($points as list("x" => $x, "y" => $y)) {
 echo "Point at ($x, $y)", PHP_EOL;
}

四、void 返回类型

PHP7.0 添加了指定函数返回类型的特性,但是返回类型却不能指定为 void,7.1 的这个特性算是一个补充:

<"htmlcode">
<"htmlcode">
<"htmlcode">
<"htmlcode">
<"color: #ff0000">五、类常量属性设定

这个特性说起来比较简单,就是现在类中的常量支持使用 publicprivate protected 修饰了:

<"htmlcode">
<"htmlcode">
<"testClass" );
$const = $obj->getReflectionConstant( "TEST_CONST" );
$consts = $obj->getReflectionConstants();

六、多条件 catch

在以往的 try ... catch 语句中,每个 catch 只能设定一个条件判断:

<"htmlcode">
<"color: #ff0000">总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用PHP7.1能有一定的帮助,如果有疑问大家可以留言交流。

附:源 RFC 地址

Nullable Types
Square bracket syntax for array destructuring assignment
Allow specifying keys in list()
Generalize support of negative string offsets
Void Return Type
Class constant visibility modifiers
Multi catch

标签:
php7.1,新特性,php7新特性

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“PHP 7.1新特性的汇总介绍”

暂无PHP 7.1新特性的汇总介绍的评论...