Laravel 5.7 展望:在 Blade 模板中使用 null 合并运算符
在下一个主要版本中,Laravel 5.7 移除了 Blade 模板的 "or" 运算符。 Andrew Brown 为 Laravel 5.7 提交了一个 移除 Blade 默认值 的 PR,因为可以使用 PHP 7 的 Null 合并运算符来代替。
虽然距 Laravel 5.7 发布还有几个月的时间,但是使用 PHP 7 的 null 合并运算符 来代替 "or" 运算符是个好主意。
PHP 7 的 Null 合并运算符#
PHP7 新引入 null 合并运算符是对 PHP 的一个很好的补充,对你的模板来说也十分有用。 它是一个语法糖,用于代替频繁使用三元运算符与 isset()
结合的情况。
根据 PHP 手册,这里有几个例子说明了它的工作原理:
<?php
// 取得 $_GET['user'] 的值,如果不存在则返回 'nobody'
$username = $_GET['user'] ?? 'nobody';
// 等价于:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// 合并运算可以链在一起: 这里会返回
// $_GET['user'], $_POST['user'],和 'nobody' 中
// 第一个被定义的值
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
你甚至可以链式调用它们,Blade 模板引擎自带的 "or" 运算符的时代结束了,它们停在了 Laravel 5.6 。
下面的几个例子解释了 null 合并运算符的工作原理,使用 PsySH REPL 演示:
$ psysh
>>> true ?? 'Is it true?'
=> true
>>> false ?? 'Is it false?'
=> false
>>> $person->getName() ?? 'Guest'
PHP Notice: Undefined variable: person on line 1
>>> $person->name ?? 'Guest'
=> "Guest"
The Background of the Blade "or" Operator#
Before the null coalescing operator, Blade handled the same problem with the "or" operator, which allows a default value when the first value isn't set, separated by an "or":
{{ $name or 'Guest' }}
Which is shorthand for:
isset($name) ? $name : 'Guest'
Laravel increased the PHP requirement to PHP 7 in Laravel 5.5, so in the previous version you could use the ??
operator if using PHP 7, but the framework needed to support PHP 5.
Update Now#
Since Laravel 5.5 requires PHP 7, you can update your usage of the "or" operator to the null coalesce operator ahead of the Laravel 5.7 release later this year.
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。
推荐文章: