Req #49543 [Opn->Csd]: closures cannot import/inherit $this

From: Date: Fri, 17 Dec 2010 11:18:13 +0000
Subject: Req #49543 [Opn->Csd]: closures cannot import/inherit $this
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-157036@lists.php.net to get a copy of this message
Edit report at http://bugs.php.net/bug.php?id=49543&edit=1

 ID:                 49543
 Updated by:         jani@php.net
 Reported by:        mjs at beebo dot org
 Summary:            closures cannot import/inherit $this
-Status:             Open
+Status:             Closed
 Type:               Feature/Change Request
-Package:            Feature/Change Request
+Package:            Scripting Engine problem
 Operating System:   Ubuntu
 PHP Version:        5.3.0
-Assigned To:        
+Assigned To:        jani
 Block user comment: N
 Private report:     N

 New Comment:

This was added in trunk (will not be in 5.3.x) but whatever trunk
becomes.


Previous Comments:
------------------------------------------------------------------------
[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 http://bugs.php.net/bug.php?id=49543&edit=1


Thread (6 messages)

« previous php.bugs (#157036) next »