The WeakMap class

(PECL weakref >= 0.2.0)

Introduction

Class synopsis

WeakMap implements Countable , ArrayAccess , Iterator {
/* Methods */
public __construct ( void )
public int count ( void )
public mixed current ( void )
public object key ( void )
public void next ( void )
public bool offsetExists ( object $object )
public mixed offsetGet ( object $object )
public void offsetSet ( object $object , mixed $value )
public void offsetUnset ( object $object )
public void rewind ( void )
public bool valid ( void )
}

Examples

Example #1 Weakmap usage example

<?php
$wm 
= new WeakMap();

$o = new StdClass;

class 
{
    public function 
__destruct() {
        echo 
"Dead!\n";
    }
}

$wm[$o] = new A;

var_dump(count($wm));
echo 
"Unsetting..\n";
unset(
$o);
echo 
"Done\n";
var_dump(count($wm));

The above example will output:

int(1)
Unsetting..
Dead!
Done
int(0)

Table of Contents

Коментарии

Автор:
PHP's implementation of WeakMap allows for iterating over the contents of the weak map, hence it's important to understand why it is sometimes dangerous and requires careful thought.

If the objects of the WeakMap are "managed" by other services such as Doctrine's EntityManager, it is never safe to assume that if the object still exists in the weak map, it is still managed by Doctrine and therefore safe to consume. 

Doctrine might have already thrown that entity away but some unrelated piece of code might still hold a reference to it, hence it still existing in the map as well.

If you are placing managed objects into the WeakMap and later iterating over the WeakMap (e.g. after Doctrine flush), then for each such object you must verify that it is still valid in the context of the source of the object.

For example assigning a detached Doctrine entity to another entity's property would result in errors about non-persisted / non-managed entities being found in the hierarchy.
2023-11-17 12:18:21
http://php5.kiev.ua/manual/ru/class.weakmap.html
Автор:
Keep in mind that if Enum case is put as a key to WeakMap, it will never be removed because it will always have unless 1 reference to it under the hood (not sure why, probably because enum is basically a constant).
Therefore, both WeakMaps below will always have key Enum::Case. However, you still are able to unset it manually:

$weakMap = new WeakMap();
$object = Enum::Case;

$weakMap[$object] = 123;
unset($object);
var_dump($weakMap->count());  // 1

///

$weakMap = new WeakMap();
$weakMap[Enum::Case] = 123;
var_dump($weakMap->count());  // 1

///

$weakMap = new WeakMap();
$weakMap[Enum::Case] = 123;
unset($weakMap[Enum::Case]);
var_dump($weakMap->count());  // 0
2024-04-02 23:19:30
http://php5.kiev.ua/manual/ru/class.weakmap.html

    Поддержать сайт на родительском проекте КГБ