PHP7.0新特性
- 标量类型声明
函数参数除了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));
- 返回值类型声明
<?php
function func(): array {
return [];
}
- 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,0,1) -
通过
define()
定义常量数组 -
匿名类
-
支持
yield from
-
yield
支持return,Generator::getReturn()
获取return的值
PHP7.1新特性
- 可为null类型声明
<?php
function testReturn(): ?string {
return 'elePHPant';
}
function test(?string $name)
{
var_dump($name);
}
- void返回类型声明
- 类常量可见性
private const PRIVATE_CONST = 4;
- 多异常捕获处理
<?php
try {
// some code
} catch (FirstException | SecondException $e) {
// handle first and second exceptions
}
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新特性
object
对象类型
<?php
function test(object $obj) : object
{
return new SplQueue();
}
test(new StdClass());
- 允许重写抽象方法
<?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新特性
- 属性类型声明
<?php
class User {
public int $id;
public string $name;
}
- 箭头函数
<?php
$factor = 10;
$nums = array_map(fn($n) => $n * $factor, [1, 2, 3, 4]);
- 空合并赋值运算符
<?php
$array['key'] ??= computeDefault();
- 数组中间unpack
<?php
$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];
- 数字支持
_
<?php
$a = 299_792_458; // decimal