Table of Contents

2. Weak Maps — Memory‑Safe Object Tracking

Weak Maps let us associate data with objects
without preventing those objects from being garbage‑collected.
They give us a way to track metadata, caches, or ephemeral state
without creating accidental memory leaks.

They reflect a broader shift in modern PHP:
memory should be explicit, predictable, and safe,
especially in long‑running processes.


1. What Weak Maps Are

A WeakMap is a special map where:

$map = new WeakMap();
 
$obj = new stdClass();
$map[$obj] = 'metadata';
 
unset($obj);   // entry is removed automatically

The map cleans itself.
No manual bookkeeping.
No accidental retention.


2. Why Modern PHP Uses Weak Maps

Weak Maps reduce:

They are especially important in:

Anywhere objects come and go,
Weak Maps keep memory honest.


3. The Mental Model

A Weak Map is a memory‑safe sidecar.

It lets us attach data to an object without owning it.

The key idea:

Use a Weak Map when you want to associate metadata with an object without extending its lifetime.

It’s a quiet, architectural tool — not something we sprinkle everywhere.


4. A Simple Example

Imagine you want to attach profiling data to objects as they flow through a system.

Without Weak Maps:

$profileData[$objectId] = $data;  // must track IDs manually

With Weak Maps: <code php> $profiles = new WeakMap(); $profiles[$object] = $data; <code> When $object goes out of scope, the entry disappears.
No cleanup.
No leaks.


5. Where Weak Maps Shine

Weak Maps are ideal when:

They shine in:

Weak Maps are a quiet architectural tool
— invisible to most developers,
essential to framework authors.


6. When Not to Use Weak Maps

Avoid them when:

Weak Maps are for ephemeral metadata,
not core state.


7. When AI Gets This Wrong

AI often:

  • uses Weak Maps where normal arrays are clearer
  • attaches persistent state to Weak Maps (which then disappears unexpectedly)
  • mixes Weak Maps with non‑object keys
  • treats Weak Maps as a general caching mechanism
  • forgets that entries vanish when objects are destroyed

Our mental model helps us see when a Weak Map expresses real memory safety
— and when AI is using it simply because it “looks advanced”.


Summary

Weak Maps let us associate metadata with objects without extending their lifetime.
They prevent memory leaks, simplify cleanup, and support long‑running processes.

Once we internalize this,
we can immediately see when AI‑generated code:

Weak Maps are a small feature
— but they teach us
how modern PHP wants to express memory‑safe architecture.