Published in
2 min readFeb 11, 2023
# Readonly classes
可以讓一個 class readonly, 也就是該 class 內的所有 property 都只能 read, 也不能動態的建立 property, 官方範例如下:
<?php
readonly class BlogData
{
public string $title;
public Status $status;
public function __construct(string $title, Status $status)
{
$this->title = $title;
$this->status = $status;
}
}
# Disjunctive normal form types (DNF)
新增一種 type, 叫做 DNF, 結合了 union 以及 intersection type, 以下的範例表示, bar function 的 argument $entity 的 type 應該是以下兩者選其一
- 同時 implement A interface 以及 B interface
- null
<?php
class Foo {
public function bar((A&B)|null $entity) {
if ($entity === null) {
return null;
}
return $entity;
}
}
# Null, false, and true stand-alone types
null, true, false 現在可以是 stand-alone type 了, 以下為官方範例:
<?php
class Falsy
{
public function alwaysFalse(): false { /* ... */ *}
public function alwaysTrue(): true { /* ... */ *}
public function alwaysNull(): null { /* ... */ *}
}
# Constants in traits
trait 內在 8.2 可以定義 constant 了, 如下範例:
<?php
trait Foo
{
public const CONSTANT = 1;
public function bar(): int
{
return self::CONSTANT; // Fatal error
}
}
class Bar
{
use Foo;
}
var_dump(Bar::CONSTANT); // 1
# Dynamic property deprecation
動態的 assign property 已經棄用, 而 stdClass 還可以用
<?php
class User
{
public $name;
}
$user = new User();
$user->last_name = 'Doe'; // Deprecated notice
$user = new stdClass();
$user->last_name = 'Doe'; // Still allowed
也可以加入 AllowDynamicProperties
attribute 來允許動態 assign property
<?php
#[AllowDynamicProperties]
class User() {}
$user = new User();
$user->foo = 'bar';
# New Classes, Interfaces, and Functions
8.2 有新增了一些 class, 細節可參考 官方文件