Re: [PATCH] [RFC] Closures and lambda functions in PHP

From: Date: Tue, 17 Jun 2008 05:57:12 +0000
Subject: Re: [PATCH] [RFC] Closures and lambda functions in PHP
References: 1 2 3  Groups: php.internals 
Request: Send a blank email to internals+get-38310@lists.php.net to get a copy of this message
On Mon, Jun 16, 2008 at 9:57 PM, Larry Garfield <larry@garfieldtech.com> wrote: > Thoughts from a user-land denizen: > > - Related to that, would it then be possible to add methods to a class at > runtime using lambda functions as the added methods? If so, how? If not, > is > that something that could reasonably be added here without hosing > performance > (or at least doing so less than stacking __call() and > call_user_func_array() > does)? im curious about this as well, and i would welcome such functionality. adding methods to class instances from within the definition of the class seems intuitive, the $this keyword should be available, but when adding methods via a variable which holds a handle to a class instance, well, i wonder, would the $this keyword be available within those anonymous function definitions? class Dynamic { private $someVar = 5; /// adding a function to instances from within the class public function addMethodAtRuntime() { $this->dynamicFunc1 = function() { return $this->someVar; // expected to work } } } /// adding a function to an instance externally $dynamic = new Dynamic(); $anotherVar = 6; $dynamic->dynamicFunc2 = function() { lexical $anotherVar; // expected to work return $this->someVar + $anotherVar; // would this work ? } /// invoking dynamically added methods /// (anticipated behavior given above definitions) $dynamic->addMethodAtRuntime(); echo $dynamic->dynamicFunc1(); // 5 echo $dynamic->dynamicFunc2(); // 11 -nathan

« previous php.internals (#38310) next »