联合类型(Union Types)

可以声明变量可能的类型,语法糖 = 鸡肋,旧版本不声明就是。

1
2
3
4
5
6
7
8
9
10
11
class Number {
private int|float $number;

public function setNumber(int|float $number): void {
$this->number = $number;
}

public function getNumber(): int|float {
return $this->number;
}
}

添加了 WeakMap

允许数组中的 key 放入对象(鸡肋),map[map[obj] = 42;。

添加了 ValueError 类。

当函数或方法接收到具有正确类型的参数(错误类型应引发 TypeError 但值不合适时,将引发 ValueError

类的变更、使用

1、可变参数继承(鸡肋),允许

1
2
3
4
5
6
class A {
public function method(int $many, string $parameters, $here) {}
}
class B extends A {
public function method(...$everything) {}
}

2、后期静态绑定(LSB)(有用),对框架级别的封装、一些工厂设计模式有用。RFC

1
2
3
4
5
class Test {
public function create(): static {
return new static();
}
}

3、现在可以使用以下方法获取对象的类名称 RFC

$object::class. 等价 get_class($object).

4、现在,new 和 instanceof 可以与任意表达式一起使用,使用

new(expression)(… $args) 和 $obj instanceof(expression)。RFC

5、现在允许写。RFC

1
Foo::BAR::$baz

6、添加 Stringable 接口(作用一般,用在视图模板封装)。RFC

只要类实现了__toString,那么这类自动实现了 Stringable 接口。

1
2
3
4
5
6
7
8
9
10
class Foo
{
public function __toString(): string
{
return 'foo';
}
}
function bar(Stringable $stringable) { /* 虽然Foo没有实现Stringable,但是这里正常的。 */ }
bar(new Foo());
bar('abc');

7、trait 现在可以定义抽象的私有方法。

现在可以将 throw 用作表达式。

原来的 throw 是语句,必须用例如 if 判断后独立抛出。(用处多)

1
2
3
// $value is non-nullable.
$value = $nullableValue ?? throw new InvalidArgumentException();

允许在参数列表中使用逗号结尾
鸡肋中的鸡肋,无用处

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Uri {
private function __construct(
?string $scheme,
?string $user,
?string $pass,
?string $host,
?int $port,
string $path,
?string $query,
?string $fragment // <-- ARGH!
) {
///...
}
}

现在可以编写 catch(Exception)来捕获异常而不将其存储在变量中。RFC

如果用不到异常信息可以不设变变量,减少内存?

1
2
3
4
5
try {
changeImportantData();
} catch (PermissionException) {
echo "You don't have permission to do this";
}

增加了对混合类型 Mixed 的支持

这个 [RFC](https://link.zhihu.com/?target=https%3A//learnku.com/articles/[https%3A//wiki.php.net/rfc/mixed_type_v2](https%3A//wiki.php.net/rfc/mixed_type_v2) 内容挺多的,建议进去看示例。

1
2
3
4
5
6
7
8
9
10
class A
{
public function foo(int $value) {}
}

class B extends A
{
// Parameter type was widened from int to mixed, this is allowed
public function foo(mixed $value) {}
}

增加了对注解 Annotations 的支持 RFC

这个功能应该期待很久了,多数用在配置,路由、事件、ORM 映射定义等等;很有用。

1
2
3
4
5
6
7
8
class Foo
{
<<ORM\Column(ORM\Column::T_INTEGER)>>
protected $height;

<<ExampleAttribute>>
public function foo(<<ExampleAttribute>> $bar) { }
}

添加了对构造函数属性提升的支持(在构造函数签名)。 RFC

语法糖,减少 Getters and Setters 代码,说实话,这部分代码还不如和 ide 开发商交涉,支持和 java 一样快捷生成更好,还减少学习成本。有用处,但不重要,鸡肋到普通之间。

1
2
3
4
5
6
7
8
9
10
11
12
13
// From:
class Test {
public function __construct(public Type $prop = DEFAULT) {}
}

// 等价于:
class Test {
public Type $prop;

public function __construct(Type $prop = DEFAULT) {
$this->prop = $prop;
}
}

即时(JIT)编译器,属于性能改进。

PHP7 就有了,但是没有正式启用和发布。PHP8 的 JIT 是一个比较重要的功能

大数据 & 密集计算,php 没有生态,而且因为 php 不支持线程,是多进程模型并发的(在利用多核 cpu 时,无法共享对象 + 语柄资源),本身就不适合密集计算