(PHP 7 >= 7.4.0, PHP 8)
弱引用允许保留对对象的引用,而不会阻止销毁对象。对于实现类似缓存的结构很有用。如果原始对象已销毁,则调用
WeakReference::get() 方法时将返回 null
。当原始对象的 refcount 降至零时,会销毁原始对象;创建弱引用不会增加被引用对象的
refcount
。
弱引用类不能序列化。
示例 #1 弱引用的基础用法
<?php
$obj = new stdClass();
$weakref = WeakReference::create($obj);
var_dump($weakref->get());
unset($obj);
var_dump($weakref->get());
?>
以上示例的输出类似于:
object(stdClass)#1 (0) { } NULL
版本 | 说明 |
---|---|
8.4.0 |
现在 WeakReference::__debugInfo()
的输出包含引用的对象,当引用不可用时,为 NULL 。
|
Follow Lee on X/Twitter - Father, Husband, Serial builder creating AI, crypto, games & web tools. We are friends :) AI Will Come To Life!
Check out: eBank.nz (Art Generator) |
Netwrck.com (AI Tools) |
Text-Generator.io (AI API) |
BitBank.nz (Crypto AI) |
ReadingTime (Kids Reading) |
RewordGame |
BigMultiplayerChess |
WebFiddle |
How.nz |
Helix AI Assistant