-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path5_weak_maps.php
51 lines (38 loc) · 1.03 KB
/
5_weak_maps.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/**
* Copyright (C) 2020 Temuri Takalandze <me@abgeo.dev>
*
* This material can not be copied and/or
* distributed without the express permission of Temuri Takalandze.
*
* Written by Temuri Takalandze <me@abgeo.dev>, November 2020
*/
class Foo
{
private WeakMap $cache;
public function __construct()
{
$this->cache = new WeakMap();
}
public function getSomethingWithCaching(object $obj)
{
echo __METHOD__ . "\n";
return $this->cache[$obj] ??= $this->computeSomethingExpensive($obj);
}
public function computeSomethingExpensive(object $obj)
{
echo __METHOD__ . "\n";
for ($i = 0; $i < 1000000; $i++) {
$obj->foo = $i;
}
return $obj->foo;
}
}
$foo = new Foo();
$object = new stdClass();
$foo->getSomethingWithCaching($object);
echo "\n-----------------------------\n\n";
$foo->getSomethingWithCaching($object);
echo "\n-----------------------------\n\n";
$object = new stdClass();
$foo->getSomethingWithCaching($object);