mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-25 04:56:23 +00:00
31 lines
706 B
Markdown
31 lines
706 B
Markdown
---
|
|
id: 7cdfd822-29cd-4b53-996f-7e7f618f754a
|
|
title: PHP Weak Maps
|
|
---
|
|
|
|
# Description
|
|
|
|
Weak maps[^1] allow creating a map from objects to arbitrary values
|
|
(similar to SplObjectStorage) without preventing the objects that are
|
|
used as keys from being garbage collected. If an object key is garbage
|
|
collected, it will simply be removed from the map. This will save a lot
|
|
of headaches for people writing things like ORMs.
|
|
|
|
# Syntax
|
|
|
|
``` php
|
|
class Foo
|
|
{
|
|
private WeakMap $cache;
|
|
|
|
public function getSomethingWithCaching(object $obj): object
|
|
{
|
|
return $this->cache[$obj]
|
|
??= $this->computeSomethingExpensive($obj);
|
|
}
|
|
}
|
|
```
|
|
|
|
# Footnotes
|
|
|
|
[^1]: <https://wiki.php.net/rfc/weak_maps>
|