Bug #71737 [Opn->Csd]: Memory leak in closure with parameter named $this

From: Date: Wed, 20 Apr 2016 16:47:27 +0000
Subject: Bug #71737 [Opn->Csd]: Memory leak in closure with parameter named $this
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-200667@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=71737&edit=1 ID: 71737 Updated by: nikic@php.net Reported by: james dot harris at icecave dot com dot au Summary: Memory leak in closure with parameter named $this -Status: Open +Status: Closed Type: Bug Package: Scripting Engine problem Operating System: OSX PHP Version: 7.0.4 Block user comment: N Private report: N New Comment: Automatic comment on behalf of nikic Revision: http://git.php.net/?p=php-src.git;a=commit;h=77bb96d7c95ddfdba8b16325db439913ee58522f Log: Fix bug #71737 Previous Comments: ------------------------------------------------------------------------ [2016-03-13 02:19:15] james dot harris at icecave dot com dot au I would hope this is very uncommon, but I did encounter it in the wild with code that was fine under PHP 5. That said, I agree absolutely that it should be forbidden, for whatever that's worth. ------------------------------------------------------------------------ [2016-03-11 23:07:49] nikic@php.net I agree with @bwoebi, this should be forbidden. ------------------------------------------------------------------------ [2016-03-08 07:10:48] bwoebi@php.net This should be just outright forbidden as Closures may be bound to a $this and we generally do prevent $this overloading in methods. php -r 'class a { function b($this) {} } (new a)->b(1);' PHP Fatal error: Cannot re-assign $this in Command line code on line 1 ------------------------------------------------------------------------ [2016-03-08 05:38:00] james dot harris at icecave dot com dot au Description: ------------ A memory leak occurs when a closure that is defined inside a class and has a parameter named $this is invoked with a value that contains a reference to $this. This gist (https://gist.github.com/jmalloc/e3db5842c2c4ab2a1edf) might help explain a little better. Affected PHP versions: https://3v4l.org/lr963 Test script: --------------- class MemoryLeak { public function bad() { $closure = function ($this) {}; $closure([$this]); } } $object = new MemoryLeak; ini_set('memory_limit', '10M'); for ($i = 0; $i < 1000000; ++$i) { $object->bad(); } echo "Done" . PHP_EOL; Expected result: ---------------- Done Actual result: -------------- Fatal error: Allowed memory size of 10485760 bytes exhausted (tried to allocate 4096 bytes) in /Users/james/<snip>/leak.php on line 8 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=71737&edit=1

« previous php.bugs (#200667) next »