mirror of
https://github.com/alrayyes/wiki.git
synced 2024-12-01 15:26:23 +00:00
37 lines
786 B
Markdown
37 lines
786 B
Markdown
|
---
|
||
|
id: 954a4b48-f3a5-4ef6-a2ea-93f843250c68
|
||
|
title: PHP Weap 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);
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
# Related
|
||
|
|
||
|
- [PHP](20201109133720-php)
|
||
|
- [PHP 8.0](20201109133834-php_8_0)
|
||
|
|
||
|
# Footnotes
|
||
|
|
||
|
[^1]: <https://wiki.php.net/rfc/weak_maps>
|