Laravel 5.7 展望:在 Blade 模板中使用 null 合并运算符

file

在下一个主要版本中,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 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://laravel-news.com/blade-templates...

译文地址:https://learnku.com/laravel/t/9407/larav...

本文为协同翻译文章,如您发现瑕疵请点击「改进」按钮提交优化建议
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!