总有人间一两风,填我十万八千梦

PHP 弱引用 用法 手册 | 示例代码

PHP开发手册 归档 266℃ 0评论

WeakReference 类

(No version information available, might only be in Git)

简介

弱引用可以指向一个对象,并且不阻止对象的销毁。可以实现具有对象结构的缓存。

弱引用类不能序列化。

类摘要

WeakReference {
/* 方法 */
public __construct()
public static create(object $object): WeakReference
public get(): object null

}

弱引用示例

示例 #1 弱引用的基础用法

<?php
$obj 
= new stdClass;
$weakref WeakReference::create($obj);
var_dump($weakref->get());
unset(
$obj);
var_dump($weakref->get());
?>

以上例程的输出类似于:

object(stdClass)#1 (0) {
}
NULL

目录

用户贡献的笔记

Sandor Toth

You might consider to use WeakReference in your Container class. Don't forget to create the object into a variable and pass the variable to WeakReference::create() otherwise you going to ->get() null.

Consider as wrong solution, which returns null
<?php
/**
* @return App
*/
public static function app() : App
{
    if (!static::
$app) {
       static::
$app = WeakReference::create(new App());
    }

    return static::$app->get();
}
?>

Consider as GOOD solution, which returns App instance
<?php
/**
* @return App
*/
public static function app() : App
{
    if (!static::
$app) {
      
$app = new App();
       static::
$app = WeakReference::create($app);
    }

    return static::$app->get();
}
?>

转载请注明:悠然品鉴 » PHP 弱引用 用法 手册 | 示例代码

喜欢 (0)or分享 (0)
发表我的评论
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址