<?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() 的实现相当于 key 只能是 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 返回类型
PHP7.0 添加了指定函数返回类型的特性,但是返回类型却不能指定为 void,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
}
}







