之前给大家介绍过php7.0的新增功能详解,今天看下php7.1和php7.2的新功能。
php7.1 新增功能
1.可为空(Nullable)类型
参数和返回值的类型声明可以通过在类型名称前添加一个问号(?)来标记为空(null)。表明函数参数或者返回值的类型要么为指定类型,要么为 null。
看下例子:
function testReturn(?string $name){ return $name;}var_dump(testReturn('yangyi'));var_dump(testReturn(null));var_dump(testReturn2());
打印输出:
$ php php71.phpstring(6) "yangyi"NULLPHP Fatal e<mark style="color:transparent">来4源gaodaimacom搞#代%码*网</mark><code>搞代gaodaima码</code>rror: Uncaught ArgumentCountError: Too few arguments to function testReturn(), 0 passed in php71.php on line 22 and exactly 1 expected in php71.php:14Stack trace:#0 php71.php(22): testReturn()#1 {main} thrown in php71.php on line 14
如上如:第三个报了一个致命的错误。
再来看下,函数返回值是Nullable的情况:
function testReturn3() : ?string{ //return "abc"; //return null;}var_dump(testReturn3());
如果加了? 要么返回 string ,要么返回null。不能啥也不返还。会报错。
2.void返回类型
PHP7.0 添加了指定函数返回类型的特性,但是返回类型却不能指定为 void,7.1 的这个特性算是一个补充。定义返回类型为 void 的函数不能有返回值,即使返回 null 也不行:
function testReturn4() : void{ //1. 要么啥都不返还 ok //2. 要么只return; ok //return; //3. return null 也会报错 //return null; //4. return 4 会报错 //return 4;}Fatal error: A void function must not return a value in /php71.php on line 70
还有就是,void 只能用于返回值,不能用于参数中。比如下面的会报错:
function testReturn6(void $a) : void{}var_dump(testReturn6());PHP Fatal error: void cannot be used as a parameter type in php71.php on line 73
如果在类的继承中,申明为void返回类型的方法,子类要是继承重写,也只能返回void, 否则会触发错误:
<?php class Foo{ public function bar(): void { }}class Foobar extends Foo{ // 覆盖失败 public function bar(): array { // Fatal error: Declaration of Foobar::bar() must be compatible with Foo::bar(): void }}
所以,你必须这样,就不会报错:
class Foo{ public $a; public function bar(): void { $this->a = 2; }}class Foobar extends Foo{ // 覆盖成功 public function bar(): void { $this->a = 3; }}
3.list 的方括号([])简写以及增加指定key
可以用list 来快速遍历得到数组里面的值。现在可以用[]简写了。
$data = [ [1, 'Tom'], [2, 'Fred'],];// list() stylelist($id1, $name1) = $data[0];// [] style[$id1, $name1] = $data[0];// list() styleforeach ($data as list($id, $name)) { // logic here with $id and $name}// [] styleforeach ($data as [$id, $name]) { // logic here with $id and $name}
此外,此次更新的list,针对索引数组,还可以指定 key,这个升级非常棒,非常方便。
$data = [ ["id" => 1, "name" => 'Tom'], ["id" => 2, "name" => 'Fred'],];// list() stylelist("id" => $id1, "name" => $name1) = $data[0];// [] style["id" => $id1, "name" => $name1] = $data[0];// list() styleforeach ($data as list("id" => $id, "name" => $name)) { // logic here with $id and $name}// [] styleforeach ($data as ["id" => $id, "name" => $name]) { // logic here with $id and $name}