|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2009-09-13 14:55 UTC] mjs at beebo dot org
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
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Thu Oct 30 12:00:01 2025 UTC |
would be nice also to have a way to alias variables when importing into the closure's scope which becomes very useful for function() use ($this as $x) { };