来源于官方RFC文档
可空类型
<?php
function answer():?int{
return null; //ok
}
function answer():?int{
return 4631.8; //4631
}
function answer(?string $v){
echo $v; //answer(null); ok
}
注意:如果函数本身定义了参数类型并且没有默认值,即使是可空的,也不能省略,否则会触发错误。
<?php
function foo_nullable(?Bar $bar) {}
foo_nullable(new Bar); // 可行
foo_nullable(null); // 可行
foo_nullable(); // 不可行
List []写法
5.4 之前数组需要通过array()定义,5.4之后可以通过[]定义。
<?php
//5.4之前
$a = array(1,2,3);
//5.4之后
$a = [1,2,3];
$a = ['a'=>1,'b'=>2,'c'=>3];
可以通过这种方式将array赋值给变量
$arr = [1,2,3];
[$a,$b,$c] = $arr;
但是不可以list(),与[]嵌套使用
<?php
// 不合法
list([$a, $b], [$c, $d]) = [[1, 2], [3, 4]];
// 不合法
[list($a, $b), list($c, $d)] = [[1, 2], [3, 4]];
// 合法
[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];
void返回类型
7.0添加了函数返回类型的特性,但是不能指定为void,7.1可以将函数返回值指定为void
<?php
function show():void{
echo 'show time';
}
指定返回void的函数不可以有返回值,null也不可以。
也不可以被子类覆盖。
类常量属性设定
常量可以使用public,private,protected修饰
为了应对变化,反射类的实现也相应的丰富了一下,增加了 getReflectionConstant
和getReflectionConstants
两个方法用于获取常量的额外属性:
<?php
class testClass {
const TEST_CONST = 'test';
}
$obj = new ReflectionClass( "testClass" );
$const = $obj->getReflectionConstant( "TEST_CONST" );
$consts = $obj->getReflectionConstants();
多条件catch
try...catch 中可以定义多个条件判断
<?php
try {
// Some code...
} catch (ExceptionType1 $e) {
// 处理 ExceptionType1
} catch (ExceptionType2 $e) {
// 处理 ExceptionType2
} catch (Exception $e) {
// ...
}
参考:
New features php7.0.x-php7.1.x