PHP 7.1 可空类型声明详解
一、可空类型声明
该特性主要应用于函数参数的类型约束以及函数返回值的类型定义中。
其实现形式主要分为以下两种场景:
<?php
function answer(): ?int {
return null; //ok
}
function answer(): ?int {
return 42; // ok
}
function say(?string $msg) {
if ($msg) {
echo $msg;
}
}
通过示例可以直观理解,即在类型前添加问号 ?,表示该参数或返回值可以是指定的具体类型,也可以是 null。
这一规则同样适用于接口中方法的定义:
<?php
interface Fooable {
function foo(?Fooable $f);
}
需特别注意:若函数参数已声明类型且未提供默认值,即便该类型是可空的,调用时也不能省略该参数,否则将引发致命错误。例如:
<?php
function foo_nullable(?Bar $bar) {}
foo_nullable(new Bar); // 可行
foo_nullable(null); // 可行
foo_nullable(); // 不可行
然而,如果将上述函数的参数定义为 ?Bar $bar = null 的形式,则第三种调用方式也是合法的。因为 = null 实际上涵盖了 ? 的功能范围,对于可空类型参数,可以直接将 null 设为默认值。
list 结构的方括号简写语法
二、list 结构的方括号简写语法
在 PHP 5.4 版本之前,定义数组必须使用 array() 关键字;5.4 版本后引入了 [] 作为简化写法(节省了5个字符输入)。
<?php
// 5.4 之前
$array = array(1, 2, 3);
$array = array("a" => 1, "b" => 2, "c" => 3);
// 5.4 及之后
$array = [1, 2, 3];
$array = ["a" => 1, "b" => 2, "c" => 3];
延伸来看,若需将数组元素分别赋值给不同变量,以往可通过 list 结构来实现:
<?php
list($a, $b, $c) = $array;
那么,是否也能利用 [] 简写来完成此操作呢?
<?php
[$a, $b, $c] = $array;
结合下文提到的 list 功能并指定 key:
<?php
["a" => $a, "b" => $b, "c" => $c] = $array;
PHP 7.1 正式支持了这一特性。但需注意:左侧赋值表达式中的 [] 并非传统意义上的数组简写,而是 list() 语法的简写形式。
不仅如此,新的 list() 机制不仅限于左值赋值,还可应用于 foreach 遍历结构中:
<?php
foreach ($points as ["x" => $x, "y" => $y]) {
var_dump($x, $y);
}
受限于当前实现细节,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]];
list 结构支持指定键名
三、list 结构支持指定键名
如前所述,新版 list() 机制允许在解构时显式指定键名:
<?php
$array = ["a" => 1, "b" => 2, "c" => 3];
["a" => $a, "b" => $b, "c" => $c] = $array;
这等效于:
<?php
$a = $array['a'];
$b = $array['b'];
$c = $array['c'];
与传统用法的区别在于,旧版 list()仅支持按 0, 1, 2, 3 等数字索引顺序解构,且无法调整顺序。执行如下代码:
<?php
list($a, $b) = [1 => '1', 2 => '2'];
将抛出 PHP error: Undefined offset: 0... 的错误提示。
而在新实现中,可以通过以下方式灵活调整赋值顺序:
<?php
list(1 => $a, 2 => $b) = [1 => '1', 2 => '2'];
与数组字面量不同,list 结构不支持混合形式的 key,以下写法会导致解析错误:
<?php
// Parse error: syntax error, ...
list($unkeyed, "key" => $keyed) = $array;
更复杂的场景下,list 也支持复合形式的解析:
<?php
$points = [
["x" => 1, "y" => 2],
["x" => 2, "y" => 1]
];
list(list("x" => $x1, "y" => $y1), list("x" => $x2, "y" => $y2)) = $points;
$points = [
"first" => [1, 2],
"second" => [2, 1]
];
list("first" => list($x1, $y1), "second" => list($x2, $y2)) = $points;
同时可在循环中使用:
<?php
$points = [
["x" => 1, "y" => 2],
["x" => 2, "y" => 1]
];
foreach ($points as list("x" => $x, "y" => $y)) {
echo "Point at ($x, $y)", PHP_EOL;
}
void 返回类型声明机制
四、void 返回类型声明
PHP 7.0 引入了函数返回类型声明功能,但当时不允许将返回类型指定为 void,PHP 7.1 对此进行了补充完善:
<?php
function should_return_nothing(): void {
return 1; // Fatal error: A void function must not return a value
}
以下两种情况均能通过验证:
<?php
function lacks_return(): void {
// valid
}
function returns_nothing(): void {
return; // valid
}
声明返回类型为 void 的函数严禁包含任何返回值,即使返回 null 也不被允许:
<?php
function returns_one(): void {
return 1; // Fatal error: A void function must not return a value
}
function returns_null(): void {
return null; // Fatal error: A void function must not return a value
}
此外,void 仅用于返回类型声明,若尝试将其用于参数类型声明,将会触发错误:
<?php
function foobar(void $foo) { // Fatal error: void cannot be used as a parameter type
}
在面向对象编程中,子类方法不能覆盖父类方法中声明的返回类型,否则将导致错误:
<?php
class Foo
{
public function bar(): void {
}
}
class Foobar extends Foo
{
public function bar(): array { // Fatal error: Declaration of Foobar::bar() must be compatible with Foo::bar(): void
}
}
类常量可见性修饰与反射
五、类常量可见性修饰
该特性较为直观,即类中的常量现在支持使用 public、private 和 protected 进行修饰:
<?php
class Token {
// 常量默认为 public
const PUBLIC_CONST = 0;
// 可以自定义常量的可见范围
private const PRIVATE_CONST = 0;
protected const PROTECTED_CONST = 0;
public const PUBLIC_CONST_TWO = 0;
// 多个常量同时声明只能有一个属性
private const FOO = 1, BAR = 2;
}
另外,接口(interface)中定义的常量只能是 public 属性:
<?php
interface ICache {
public const PUBLIC = 0;
const IMPLICIT_PUBLIC = 1;
}
为了适配这一变化,反射类的实现也得到了增强,新增了 getReflectionConstant 和 getReflectionConstants 两个方法,用于获取常量的额外属性信息:
<?php
class testClass {
const TEST_CONST = 'test';
}
$obj = new ReflectionClass( "testClass" );
$const = $obj->getReflectionConstant( "TEST_CONST" );
$consts = $obj->getReflectionConstants();
多条件异常捕获简化处理
六、多条件异常捕获
在以往的 try ... catch 语句中,每个 catch 块只能针对单一异常类型进行判断:
<?php
try {
// Some code...
} catch (ExceptionType1 $e) {
// 处理 ExceptionType1
} catch (ExceptionType2 $e) {
// 处理 ExceptionType2
} catch (\Exception $e) {
// ...
}
新实现允许在一个 catch 块中设置多个异常类型,相当于逻辑或的判断方式:
<?php
try {
// Some code...
} catch (ExceptionType1 | ExceptionType2 $e) {
// 对于 ExceptionType1 和 ExceptionType2 的处理
} catch (\Exception $e) {
// ...
}
这显著简化了异常处理的代码结构。
总结
以上就是本文介绍的全部内容,希望这些内容能帮助大家更好地学习或使用 PHP 7.1。如有任何疑问,欢迎留言交流。
附:相关 RFC 源地址
Nullable Types Square bracket syntax for array destructuring assignment Allow specifying keys in list() Generalize support of negative string offsets Void Return Type Class constant visibility modifiers Multi catch