smallyu的博客

smallyu的博客

马上订阅 smallyu的博客 RSS 更新: https://smallyu.net/atom.xml

PHP 7,让代码更优雅(译)

2018年11月1日 22:19

PHP 7已发布很久,它可以让代码更加简洁,让我们一睹其风采。

标量类型声明

标量指string、int、float和bool。PHP 7之前,如果要验证一个函数的参数类型,需要手动检测并抛出异常:

<?phpfunction add($num1, $num2) {    if (!is_int($num1)) {        throw new Exception("$num1 is not an integer");    }    if (!is_int($num2)) {        throw new Exception("$num2 is not an integer");    }    return ($num1 + $num2);}echo add(2, 4);     // 6echo add(1.5, 4);   // Fatal error: Uncaught Exception

现在,可以直接声明参数类型:

<?phpfunction add(int $num1, int $num2) {    return ($num1 + $num2);}echo add(2, 4);     // 6echo add("2", 4);   // 6echo add("sonething", 4);   // Fatal error: Uncaught TypeError

由于PHP默认运行在coercive模式,所以”2”被成功解析为2。可以使用declare函数启用严格模式:

<?phpdeclare(strict_types=1);function add(int $num1, int $num2) {    return ($num1 + $num2);}echo add(2, 4);     // 6echo add("2", 4);   // Fatal error: Uncaught TypeError

返回类型声明

像参数一样,现在返回值也可以指定类型:

<?phpfunction add($num1, $num2):int {    return ($num1 + $num2);}echo add(2, 4);     // 6echo add(2.5, 4);   // 6

2.5 + 4返回了int类型的6,这是隐式类型转换。如果要避免隐式转换,可以使用严格模式来抛出异常:

<?phpdeclare(strict_types=1);function add($num1, $num2):int{    return ($num1 + $num2);}echo add(2, 4); //6echo add(2.5, 4); //Fatal error: Uncaught TypeError

空合并运算符

在PHP5中,检测一个变量,如果未定义则为其赋初值,实现起来需要冗长的代码:

$username = isset($_GET['username]') ? $_GET['username'] : '';

在PHP 7中,可以使用新增的”??”运算符:

$username = $_GET['username'] ?? '';

这虽然仅仅是一个语法糖,但能让我们的代码简洁不少。

太空船运算符

也叫组合运算符,用于比较两表达式的大小。当$a小于、等于、大于$b时,分别返回-1、0、1。

echo 1 <=> 1;   // 0echo 1 <=> 2;   // -1echo 2 <=> 1;   // 1

批量导入声明

在相同命名空间下的类、函数、常量,现在可以使用一个use表达式一次导入:

<?php// PHP 7之前use net\smallyu\ClassA;use net\smallyu\ClassB;use net\smallyu\ClassC as C;use function net\smallyu\funA;use function net\smallyu\funB;use function net\smallyu\funC;use const net\smallyu\ConstA;use const net\smallyu\ConstB;use const net\smallyu\ConstC;// PHP 7use net\smallyu\{ClassA, ClassB, ClassC};use function net\smallyu\{funA, funB, funC};use const net\smallyu\{ConstA, ConstB,...

剩余内容已隐藏

查看完整文章以阅读更多