PHP7.*新特性

PHP7.0新特性

  1. 标量类型声明

函数参数除了array,class,interface, callable,目前支持int,string,bool,float标量声明。

<?php
// Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

var_dump(sumOfInts(2, '3', 4.1));
  1. 返回值类型声明
<?php
function func(): array {
    return [];
 }
  1. null合并运算符 ??
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
  1. 太空船操作符 <=> 比较大小返回(-1,0,1)

  2. 通过 define() 定义常量数组

  3. 匿名类

  4. 支持 yield from

  5. yield支持return,Generator::getReturn() 获取return的值

PHP7.1新特性

  1. 可为null类型声明
<?php
function testReturn(): ?string {
    return 'elePHPant';
}

function test(?string $name)
{
    var_dump($name);
}
  1. void返回类型声明
  2. 类常量可见性 private const PRIVATE_CONST = 4;
  3. 多异常捕获处理
<?php
try {
    // some code
} catch (FirstException | SecondException $e) {
    // handle first and second exceptions
}
  1. list()支持键名
foreach ($data as list("id" => $id, "name" => $name)) {
    // logic here with $id and $name
}

// [] style
foreach ($data as ["id" => $id, "name" => $name]) {
    // logic here with $id and $name
}

PHP7.2新特性

  1. object对象类型
<?php

function test(object $obj) : object
{
    return new SplQueue();
}

test(new StdClass());
  1. 允许重写抽象方法
<?php

abstract class A
{
    abstract function test(string $s);
}

abstract class B extends A
{
    // overridden - still maintaining contravariance for parameters and covariance for return
    abstract function test($s) : int;
}

PHP7.3新特性

PHP7.4新特性

  1. 属性类型声明
<?php
class User {
    public int $id;
    public string $name;
}
  1. 箭头函数
<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
  1. 空合并赋值运算符
<?php
$array['key'] ??= computeDefault();
  1. 数组中间unpack
<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
  1. 数字支持_
<?php
$a = 299_792_458;   // decimal

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注