2024 年 PHP Conference Japan
已發佈!
PHP 8.2 是 PHP 語言的主要更新版本。
它包含許多新功能,包括唯讀類別、null、false 和 true 作為獨立類型、棄用動態屬性、效能提升等等。

唯讀類別 RFC 文件

PHP < 8.2
類別 BlogData
{
public readonly
string $title;

public readonly
Status $status;

public function
__construct(string $title, Status $status)
{
$this->title = $title;
$this->status = $status;
}
}
PHP 8.2
唯讀類別 BlogData
{
public
string $title;

public
Status $status;

public function
__construct(string $title, Status $status)
{
$this->title = $title;
$this->status = $status;
}
}

析取正規型式 (DNF) 類型 RFC 文件

PHP < 8.2
類別 Foo {
public function
bar(mixed $entity) {
if (((
$entity instanceof A) && ($entity instanceof B)) || ($entity === null)) {
return
$entity;
}

throw new
Exception('無效的實體');
}
}
PHP 8.2
類別 Foo {
public function
bar((A&B)|null $entity) {
return
$entity;
}
}
DNF 類型允許我們組合聯集交集類型,並遵循一個嚴格的規則:當組合聯集和交集類型時,交集類型必須用括號分組。

允許 nullfalsetrue 作為獨立類型 RFC RFC

PHP < 8.2
類別 Falsy
{
public function
almostFalse(): bool { /* ... */ }

public function
almostTrue(): bool { /* ... */ }

public function
almostNull(): string|null { /* ... */ }
}
PHP 8.2
類別 Falsy
{
public function
alwaysFalse(): false { /* ... */ }

public function
alwaysTrue(): true { /* ... */ }

public function
alwaysNull(): null { /* ... */ }
}

新的「Random」擴充功能 RFC RFC 文件

PHP 8.2
使用 Random\Engine\Xoshiro256StarStar;
使用
Random\Randomizer;

$blueprintRng = new Xoshiro256StarStar(
hash('sha256', "範例種子,透過 SHA-256 轉換為 256 位元字串", true)
);

$fibers = [];
for (
$i = 0; $i < 8; $i++) {
$fiberRng = clone $blueprintRng;
// Xoshiro256** 的 'jump()' 方法會將 blueprint 向前推進 2**128 步,如同呼叫
// 'generate()' 2**128 次,賦予 Fiber 2**128 個獨特值,而無需重新設定種子。
$blueprintRng->jump();

$fibers[] = new Fiber(function () use ($fiberRng, $i): void {
$randomizer = new Randomizer($fiberRng);

echo
"{$i}: " . $randomizer->getInt(0, 100), PHP_EOL;
});
}

// 隨機產生器預設會使用 CSPRNG。
$randomizer = new Randomizer();

// 即使 fibers 以隨機順序執行,它們每次都會印出相同的值,
// 因為每個 fiber 都有其獨特的 RNG 實例。
$fibers = $randomizer->shuffleArray($fibers);
foreach (
$fibers as $fiber) {
$fiber->start();
}

「random」擴充套件提供了一個新的物件導向 API 來產生隨機數。它不再依賴使用 Mersenne Twister 演算法的全局設定種子的隨機數產生器 (RNG),物件導向 API 提供了幾個類別(「Engine」),可以存取現代演算法,這些演算法將其狀態儲存在物件內,允許多個獨立的可設定種子的序列。

\Random\Randomizer 類別提供了一個高階介面,可以使用引擎的隨機性來產生隨機整數、洗牌陣列或字串、選擇隨機陣列鍵等等。

特性中的常數 RFC 文件

PHP 8.2
trait Foo
{
public const
CONSTANT = 1;
}

class
Bar
{
use
Foo;
}

var_dump(Bar::CONSTANT); // 1
var_dump(Foo::CONSTANT); // 錯誤
您無法透過特徵 (trait) 的名稱來存取常數,但您可以透過使用該特徵的類別來存取常數。

動態屬性已被棄用 RFC 文件

PHP < 8.2
class User
{
public
$name;
}

$user = new User();
$user->last_name = 'Doe';

$user = new stdClass();
$user->last_name = 'Doe';
PHP 8.2
class User
{
public
$name;
}

$user = new User();
$user->last_name = 'Doe'; // 已棄用通知

$user = new stdClass();
$user->last_name = 'Doe'; // 仍然允許

除非類別使用 #[\AllowDynamicProperties] 屬性選擇加入,否則建立動態屬性已被棄用,以協助避免錯誤和拼寫錯誤。 stdClass 允許動態屬性。

此變更不影響魔術方法 __get/__set 的使用。

棄用和向後相容性中斷

To Top