PHP 中的弱對映是什麼?
弱對映已新增到 PHP 7.4 中。它可用於在快取引用物件實體類時刪除或刪除物件。它引用這些物件,不會避免記憶體垃圾回收物件。在 PHP 8 中,弱對映允許我們儲存連結到物件的隨機資料,而不會洩漏任何記憶體。
換句話說,PHP 8 中的弱對映是一組物件,其中鍵弱引用。弱對映使用類建立一個可作為鍵使用的物件,這有助於在沒有進一步引用時刪除和銷燬弱對映。從長遠來看,它可以避免記憶體洩漏,從而最終提高效能。
我們可以說弱對映作為自動垃圾回收過程。每當刪除變數時,PHP 會檢查是否有任何變數仍引用該物件。如果變數沒有引用,則 PHP 將安全地刪除該物件。此過程稱為垃圾回收。
示例:PHP 8 弱對映
<?php
class WeakExample {
public WeakMap $cache;
public function __construct() {
$this->cache = new WeakMap();
}
public function getCaching(object $obj) {
return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj);
}
public function computeSomethingExpensive(object $obj) {
print_r("Object called");
return rand(1, 100);
}
}
$cacheObject = new stdClass;
$obj = new WeakExample;
$obj->getCaching($cacheObject);
$obj->getCaching($cacheObject);
print_r(count($obj->cache));
unset($cacheObject); // unsetting the objects and Weak Maps frees up memory
print_r(count($obj->cache));
?>輸出
Object called 1 0
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP