The WeakMap class

(PHP 8)

Introduction

A WeakMap is map (or dictionary) that accepts objects as keys. However, unlike the otherwise similar SplObjectStorage, an object in a key of WeakMap does not contribute toward the object's reference count. That is, if at any point the only remaining reference to an object is the key of a WeakMap, the object will be garbage collected and removed from the WeakMap. Its primary use case is for building caches of data derived from an object that do not need to live longer than the object.

WeakMap implements ArrayAccess, Iterator, and Countable, so in most cases it can be used in the same fashion as an associative array.

Class synopsis

final class WeakMap implements ArrayAccess, Countable, IteratorAggregate {
/* Methods */
public __construct()
public count(): int
public offsetExists(object $object): bool
public offsetGet(object $object): mixed
public offsetSet(object $object, mixed $value): void
public offsetUnset(object $object): 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

Here you can write a comment


Please enter at least 10 characters.
Loading... Please wait.
* Pflichtangabe
There are no comments available yet.

News for PHP developers: Laravel 11 release

On March 12, 2024, the long-awaited version 11 of the Laravel framework was released, bringing with it a number of exciting new features and improvements for the PHP development community. ...

Mike94

Autor : Mike94
Category: PHP Magazin

Technical SEO remains relevant

Technical SEO - What is it anyway? Technical SEO refers to the optimization of the technical aspects of your website. The goal is clear! ...

admin

Autor : admin
Category: SEO & Online-Marketing

What's new in PHP 8.2.10

PHP 8.2.10 is one of the latest versions of PHP, which brings a number of improvements and new features. In this article we will discuss some of the outstanding new features and improvements in this version. ...

admin

Autor : admin
Category: Software-Updates

Publish a tutorial

Share your knowledge with other developers worldwide

Share your knowledge with other developers worldwide

You are a professional in your field and want to share your knowledge, then sign up now and share it with our PHP community

learn more

Publish a tutorial