note 116694 added to iteratoraggregate.getiterator

From: Date: Thu, 12 Feb 2015 12:57:44 +0000
Subject: note 116694 added to iteratoraggregate.getiterator
Groups: php.notes 
Request: Send a blank email to php-notes+get-201705@lists.php.net to get a copy of this message
Be careful when caching the iterator AND supplying the iterator with a back reference to the IteratorAggregate implementor. This can cause a potential memory leak. <?php class MyClass implements IteratorAggregate { public $data; protected $iterator; public function getIterator() { // This is the culprit. Combined with the passing of $this, // neither this object nor the iterator will be destroyed until // php has finished execution and cleans up. return $this->iterator ? $this->iterator : $this->iterator = new MyIterator($this); } public function __construct($data) { print "CONSTRUCTING MyClass!\n"; $this->data = $data; } public function __destruct() { print "DESTROYING MyClass!\n"; } } class MyIterator implements Iterator { protected $obj; public function __construct($obj) { print "CONSTRUCTING MyIterator!\n"; $this->obj = $obj; } public function current() { return current($this->obj->data); } public function key() { return key($this->obj->data); } public function next() { return next($this->obj->data); } public function rewind() { return reset($this->obj->data); } public function valid() { return key($this->obj->data) !== NULL; } public function __destruct() { print "DESTROYING MyIterator!\n"; } } function test1() { $a = new MyClass(array(1, 2, 3, 4)); foreach ($a as $k => $v) { print "$k => $v\n"; } print "Iteration done!\n"; } test1(); print "test1 done\n"; ?> Expected result -------------------- CONSTRUCTING MyClass! CONSTRUCTING MyIterator! 0 => 1 1 => 2 2 => 3 3 => 4 DESTROYING MyIterator! Iteration done! DESTROYING MyClass! test1 done Actual result -------------------- CONSTRUCTING MyClass! CONSTRUCTING MyIterator! 0 => 1 1 => 2 2 => 3 3 => 4 Iteration done! test1 done DESTROYING MyClass! DESTROYING MyIterator! ---- Server IP: 72.52.91.14 Probable Submitter: 109.202.128.38 ---- Manual Page -- http://php.net/manual/en/iteratoraggregate.getiterator.php Edit -- https://master.php.net/note/edit/116694 Del: integrated -- https://master.php.net/note/delete/116694/integrated Del: useless -- https://master.php.net/note/delete/116694/useless Del: bad code -- https://master.php.net/note/delete/116694/bad+code Del: spam -- https://master.php.net/note/delete/116694/spam Del: non-english -- https://master.php.net/note/delete/116694/non-english Del: in docs -- https://master.php.net/note/delete/116694/in+docs Del: other reasons-- https://master.php.net/note/delete/116694 Reject -- https://master.php.net/note/reject/116694 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#201705) next »