{
    "slug": "php_weak_map",
    "term": "WeakMap (PHP 8.0)",
    "category": "php",
    "difficulty": "advanced",
    "short": "A map keyed by objects that doesn't prevent garbage collection — ideal for caching per-object computed data without creating memory leaks.",
    "long": "A WeakMap holds object keys weakly — when the only remaining reference to a key object is in the WeakMap, that object is garbage collected and its WeakMap entry is automatically removed. This contrasts with SplObjectStorage and arrays, which hold strong references and prevent GC. Typical use cases: per-object caches (memoising computed values on an entity without modifying the entity class), attribute caches in ORMs, and proxy metadata storage. WeakMap is iterable and Countable. PHP 8.0+; the RFC was specifically motivated by Doctrine's need to associate metadata with entities without preventing their deallocation.",
    "aliases": [
        "WeakMap",
        "PHP 8 WeakMap",
        "weak map PHP"
    ],
    "tags": [
        "php8",
        "php",
        "memory",
        "data-structures"
    ],
    "misconception": "WeakMap and WeakReference serve the same purpose. WeakReference is a pointer to an object that does not prevent GC. WeakMap is a key-value store keyed on objects where entries are automatically removed when the key object is garbage collected — ideal for associating metadata with objects without preventing their cleanup.",
    "why_it_matters": "WeakMap (PHP 8.0) stores key-value pairs keyed by objects without preventing garbage collection — perfect for caches and memoization where objects should not be kept alive solely because they are cache keys.",
    "common_mistakes": [
        "Using a regular array or SplObjectStorage for object-keyed caches — holds strong references, preventing GC.",
        "Not checking if a WeakMap key still exists before access — the object may have been collected.",
        "Using WeakMap for non-object keys — it only accepts objects as keys.",
        "Not realising WeakMap is not iterable when the GC runs between iterations — do not iterate a WeakMap."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "memory_leak",
        "garbage_collection",
        "spl_data_structures",
        "object_pooling"
    ],
    "prerequisites": [
        "memory_management",
        "garbage_collection",
        "php_concurrency_options"
    ],
    "refs": [
        "https://www.php.net/manual/en/class.weakmap.php"
    ],
    "bad_code": "// Regular array cache — prevents GC of $user objects:\nclass Cache {\n    private array $data = [];\n    public function set(object $key, mixed $val): void {\n        $this->data[spl_object_id($key)] = $val; // Strong reference via ID\n    }\n}\n\n// WeakMap — GC can collect $user when no other references exist:\n$cache = new WeakMap();\n$cache[$user] = computeExpensiveData($user); // Freed when $user is GC'd",
    "good_code": "$cache = new WeakMap();\nfunction expensiveData(object $obj, WeakMap $cache): array {\n    return $cache[$obj] ??= computeExpensiveData($obj);\n    // Entry removed automatically when $obj is garbage collected\n}",
    "quick_fix": "Use WeakMap when you need to associate data with object instances without preventing garbage collection — ideal for caches keyed by object references",
    "severity": "low",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/php_weak_map",
        "html_url": "https://codeclaritylab.com/glossary/php_weak_map",
        "json_url": "https://codeclaritylab.com/glossary/php_weak_map.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[WeakMap (PHP 8.0)](https://codeclaritylab.com/glossary/php_weak_map) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/php_weak_map"
            }
        }
    }
}