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

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to