#49543 [NEW]: closures cannot import/inherit $this

From: Date: Sun, 13 Sep 2009 14:55:51 +0000
Subject: #49543 [NEW]: closures cannot import/inherit $this
Groups: php.bugs 
Request: Send a blank email to php-bugs+get-142301@lists.php.net to get a copy of this message
From: mjs at beebo dot org Operating system: Ubuntu PHP version: 5.3.0 PHP Bug Type: Scripting Engine problem Bug description: closures cannot import/inherit $this Description: ------------ Attempting to import/inherit $this produces the compile-time error "Cannot use $this as lexical variable." Note that the workaround of assigning $this to the temporary variable $tmp, and inheriting $tmp instead does work, so there appears to be no limitation in the engine: class Foo { public function bar() { $tmp = $this; return function() use ($tmp) { echo "in closure\n"; } } } See also http://wiki.php.net/rfc/closures/removal-of-this. (It appears that $this was once automatically imported into the closure's scope, but that this turned out to be a bad idea. This bug report concerns what happens when $this is explicitly imported, however.) Reproduce code: --------------- <?php class Foo { public function bar() { return function() use ($this) { echo "in closure\n"; } } } Expected result: ---------------- in closure Actual result: -------------- PHP Fatal error: Cannot use $this as lexical variable in /mnt/hgfs/workspace/scratch/wart2.php on line 7 -- Edit bug report at http://bugs.php.net/?id=49543&edit=1 -- Try a snapshot (PHP 5.2): http://bugs.php.net/fix.php?id=49543&r=trysnapshot52 Try a snapshot (PHP 5.3): http://bugs.php.net/fix.php?id=49543&r=trysnapshot53 Try a snapshot (PHP 6.0): http://bugs.php.net/fix.php?id=49543&r=trysnapshot60 Fixed in SVN: http://bugs.php.net/fix.php?id=49543&r=fixed Fixed in SVN and need be documented: http://bugs.php.net/fix.php?id=49543&r=needdocs Fixed in release: http://bugs.php.net/fix.php?id=49543&r=alreadyfixed Need backtrace: http://bugs.php.net/fix.php?id=49543&r=needtrace Need Reproduce Script: http://bugs.php.net/fix.php?id=49543&r=needscript Try newer version: http://bugs.php.net/fix.php?id=49543&r=oldversion Not developer issue: http://bugs.php.net/fix.php?id=49543&r=support Expected behavior: http://bugs.php.net/fix.php?id=49543&r=notwrong Not enough info: http://bugs.php.net/fix.php?id=49543&r=notenoughinfo Submitted twice: http://bugs.php.net/fix.php?id=49543&r=submittedtwice register_globals: http://bugs.php.net/fix.php?id=49543&r=globals PHP 4 support discontinued: http://bugs.php.net/fix.php?id=49543&r=php4 Daylight Savings: http://bugs.php.net/fix.php?id=49543&r=dst IIS Stability: http://bugs.php.net/fix.php?id=49543&r=isapi Install GNU Sed: http://bugs.php.net/fix.php?id=49543&r=gnused Floating point limitations: http://bugs.php.net/fix.php?id=49543&r=float No Zend Extensions: http://bugs.php.net/fix.php?id=49543&r=nozend MySQL Configuration Error: http://bugs.php.net/fix.php?id=49543&r=mysqlcfg

« previous php.bugs (#142301) next »