🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
**一.什么是WeakMap弱映射** #WeakMap中键中存的是另一个对象的引用,这个引用是一种弱映射关系,一旦另一个对象的引用断开即想删除对象,弱映射就会断开. &emsp; **二.对象引用讲解和栈堆关系** ``` $a=new StdClass; $b=$a; unset($a); var_dump($b); ``` &emsp; **三.splObjectStorage讲解** ``` $map = new splObjectStorage(); $object = new stdClass(); $map[$object] = 'Foo'; var_dump(count($map)); unset($object); var_dump(count($map)); ``` &emsp; **四.WeakMap讲解** ``` $map = new WeakMap(); $object = new stdClass(); $map[$object] = 'Foo'; var_dump(count($map)); unset($object); var_dump(count($map)); ``` &emsp; **五.WeakMap类结构** ``` WeakMap implements Countable , ArrayAccess , Iterator { /* 方法 */ public __construct ( ) public count ( ) : int public current ( ) : mixed public key ( ) : object public next ( ) : void public offsetExists ( object $object ) : bool public offsetGet ( object $object ) : mixed public offsetSet ( object $object , mixed $value ) : void public offsetUnset ( object $object ) : void public rewind ( ) : void public valid ( ) : bool } #迭代器用法 $map = new WeakMap(); $object = new stdClass(); $map[$object] = 'Foo'; $iterator = $map->getIterator(); #key和current用法 var_dump($iterator->key()); var_dump($iterator->current()); var_dump($iterator->next()); #foreach迭代 foreach($iterator as $key=>$value){ echo $key::class.'----'.$value; } ``` &emsp; **六.splObjectStorage存储对象和引用,WeakMap只能存储引用** ``` $map = new splObjectStorage(); $map[new stdClass()] = 'Foo'; count($map); $map = new WeakMap(); $map[new stdClass()] = 'Foo'; count($map); ``` &emsp; **七.WeakMap迭代** ``` $map = new WeakMap(); $obj1 = new stdClass(); $map[$obj1] = 'Object 1'; foreach ($map as $key => $value) { var_dump($key); var_dump($value); } ``` &emsp; **八.迭代器** ``` function Gen() { yield 'user1' => '123'; yield 'user2' => '456'; yield 'user3' => '789'; } $gen = Gen(); foreach($gen as $key=>$value){ echo "$key,$value <br>"; } var_dump($gen instanceof Iterator); ``` &emsp; **九.WeakMap也可生成iterator迭代器进行迭代** ``` $map = new WeakMap(); $obj1 = new stdClass(); $map[$obj1] = 'Object 1'; $iterator = $map->getIterator(); var_dump($gen instanceof Iterator); foreach ($iterator as $key => $value) { var_dump($key); var_dump($value); echo "$key,$value"; } ``` &emsp; **配套的PHP8新特性详解视频教程,请查看以下专辑** 链接:[https://www.ixigua.com/6937490165329822219](https://www.ixigua.com/6937490165329822219)