Php7版本后的新特性

PHP 7显著地改进了整体性能。确实有一些主要的特性,比如空合并操作符或返回类型声明。如果您不知道,可以通过查看文档去了解它们。

下面是一些可能有用的不太为人所知的特性。

命名空间

//before php7
use Universe\Saiyan;
use Universe\SuperSaiyan;
//in php7
use Universe\{Saiyan, SuperSaiyan};

常量数组

define('NAMES', [
    'first'  => 'John',
    'middle' => 'Fitzgerald',
    'last'   => 'Kennedy'
]);

echo NAMES['last']; //displays "Kennedy"

太空船船操作符<=>

  • 0: 相等
  • 1: 左边的值大
  • -1: 右边的值大

    $actressesWithAcademyAwards = [
    [ ‘name’ => ‘Katharine Hepburn’, ‘awards’ => 4 ],
    [ ‘name’ => ‘Jessica Lange’, ‘awards’ => 2 ],
    [ ‘name’ => ‘Meryl Streep’, ‘awards’ => 3 ],
    [ ‘name’ => ‘Cate Blanchett’, ‘awards’ => 2 ],
    ];
    usort($actressesWithAcademyAwards, function ($a, $b) {
    return $a[‘awards’] <=> $b[‘awards’];
    });

    print_r($actressesWithAcademyAwards);

数组第一/最后一键【php7.4】

$array = [ 'v' => 1, 'i' => 2, 'p' => 3 ];

$firstKey = array_key_first($array);
$lastKey = array_key_last($array);

print_r($firstKey); // v
print_r($lastKey); // p

扩展操作符【php7.4】

$abc = range('a', 'c');
$def = range('d', 'f');
$ghi = range('g', 'i');
$all = [...$abc, ...$def, ...$ghi, 'j'];
print_r($all);
//output
/*
Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => e
    [5] => f
    [6] => g
    [7] => h
    [8] => i
    [9] => j
)*/

Arrow 函数【php7.4】

$c = 3;
$addC = fn($x) => $x + $c;
echo $addC(70); // 73

常量访问控制

class Mother {
    private const ERROR_LEVEL_1 = 'achtung';
}
你应该知道JavaScript中的7种原生错误
如何解决http405问题?
ajax-loader