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

From: Date: Tue, 17 Jun 2008 07:44:58 +0000
Subject: Re: [PATCH] [RFC] Closures and lambda functions in PHP
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-38313@lists.php.net to get a copy of this message
Hi!
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
      }
} } /// invoking dynamically added methods /// (anticipated behavior given above definitions) $dynamic->addMethodAtRuntime(); echo $dynamic->dynamicFunc1(); // 5
This will not work - for the same reason as this does not work: class SpecialChars { public $process = 'htmlspecialchars'; } $sc = new SpecialChars (); var_dump ($sc->process ('<>')); // call to undefined ... On the other hand, the following will work: $sc = new SpecialChars (); $processor = $sc->process; var_dump ($processor ('<>')); // string(8) "&lt;&gt;" The same with closures: echo $dynamic->dynamicFunc1(); // call to undefined ... $func = $dynamic->dynamicFunc1; echo $func (); // 5 echo call_user_func ($dynamic->dynamicFunc1); // 5 As I sead in my other mail: I don't see closures as a method for somehow making it possible to extend classes dynamically - if you want that, use runkit. Regards, Christian

« previous php.internals (#38313) next »