php7页面刷新,PHP7.1中的重大更新

RFC提供了更多的控制阵列的解构。上面的代码可以改为:

list("a" => $a, "b" => $b, "c" => $c) = ["a" => 1, "b" => 2, "c" => 3];

var_dump($a, $b, $c); // int(1) int(2) int(3)

上面的例子可以写成:

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

var_dump($a, $b, $c); // int(1) int(2) int(3)

很酷对不对?它还适用于多维数组:

[[$a, $b], [$c, $d]] = [[1, 2], [3, 4]];

var_dump($a, $b, $c, $d); // int(1) int(2) int(3) int(4)[["b" => $b], ["c" => $c]] = [["a" => 1, "b" => 2], ["c" => 3, "d" => 4]];

var_dump($b, $c); // int(2) int(3)

Iterable 伪类

PHP 7.1 新引入了一个被称为 iterable  的伪类。

它可以被用在参数或者返回值类型中,它代表接受数组或者实现了 Traversable 接口的对象。以下面的代码为例:

// PHP 5.6

function dump(array $items){

var_dump($items);

}

dump([2, 3, 4]);

dump(new Collection());

array(3) {

[0]=>int(2)

[1]=>int(3)

[2]=>int(4)

} Catchable fatal error: Argument 1 passed to dump() must be of the type array, object given...

但在这种情况下,函数不会接受一个价值,将抛出一个错误。这一新的变化,让你使用迭代来描述而不是手动一个价值主张。

// PHP 7.1

function dump(iterable $items){

var_dump($items);

}

dump([2, 3, 4]);

dump(new Collection());

array(3) {

[0]=>int(2)

[1]=>int(3)

[2]=>int(4)

} object(Collection)#2 (0) {}

void返回类型

这是我最喜欢的新功能之一。PHP 7添加了指定函数返回类型的特性,一个新的返回值类型 void 被引入。试图去获取一个void 方法的返回值时,将被迫返回null!并且不会产生任何警告。

function dump($object): void{

var_dump($object);

} 返回类型声明为 void 类型的方法要么干脆省去 return 语句,要么添加一个空的函数(return;)。

类常量的可见性

虽然这是个很小的变化,但是加强了面向对象的封装,现在起支持设置类常量的可见性:

class Post{

protected const PUBLISHED = 1;

protected const DRAFT = 2;

protected const TRASHED = 3; // ...

} 捕获多个异常类型

在以往的try... catch 语句中,每个catch 只能设定一个条件判断,新的版本可以在一个 catch 中设置多个条件,从而减少了需要复制的代码。 Java 等其他语言同样具备这种能力。以下面的代码为例:

// ...

try {

$user->payMonth($month);

} catch (UserSuspendedException $ex) {

DB::rollBack();

return redirect()

->back()

->withInput()

->withErrors([$ex->getMessage()]);

} catch (PaidMonthException $e) {

DB::rollBack();

return redirect()

->back()

->withInput()

->withErrors([$ex->getMessage()]);

}// ...

英文原文:https://www.sitepoint.com/whats-new-and-exciting-in-php-7-1/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值