Edit report at https://bugs.php.net/bug.php?id=49543&edit=1
ID: 49543
Comment by: netmosfera at email dot it
Reported by: mjs at beebo dot org
Summary: closures cannot import/inherit $this
Status: Closed
Type: Feature/Change Request
Package: Scripting Engine problem
Operating System: Ubuntu
PHP Version: 5.3.0
Assigned To: jani
Block user comment: N
Private report: N
New Comment:
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) { };
Previous Comments:
------------------------------------------------------------------------
[2011-06-13 06:15:05] [email protected]
It is in 5.4
------------------------------------------------------------------------
[2011-06-13 04:28:01] php at hotblocks dot nl
When can we expect this? Go PHP mixins!
------------------------------------------------------------------------
[2010-12-17 12:18:12] [email protected]
This was added in trunk (will not be in 5.3.x) but whatever trunk becomes.
------------------------------------------------------------------------
[2010-06-11 19:17:36] martin dot partel at gmail dot com
The '$tmp' workaround is not good enough, since private/protected members
cannot be accessed that way. This renders closures frustratingly useless in OO
code in quite a few situations.
All other OO languages with closures that I know of allow such access one way
or the other. Come on guys, find your consensus and get it done!
------------------------------------------------------------------------
[2009-09-13 14:55:50] 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
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=49543&edit=1