PHP 7.1 新特性

来源于官方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修饰

为了应对变化,反射类的实现也相应的丰富了一下,增加了 getReflectionConstantgetReflectionConstants 两个方法用于获取常量的额外属性:

<?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) {
    // ...
} 
参考:

php7.1新特性

New features php7.0.x-php7.1.x



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值