Hi,

- I am a little confused about the OOP interaction. How does a function become a public method of the class?

To clarify: the "public method" ist just the internal representation of
the lambda function and has *nothing* to do with the semantics of
calling the lambda itself. The "method" only means that the lambda
function defined inside another method can access the class members and
"public" only means that the lambda function can still be called from
outside the class.

class Example {
  private $a = 2;

  function myMethod($b) {
    $lambda = function() {
      lexical $b;
      return $this->a * $b; // This part I get
    };
    return $lambda;
  }
}

$e = new Example();
$lambda = $e->myMethod();
$e->$lambda(5);

No, that's not what my patch does. My patch does:

class Example {
  private $a = 2;

  public function myMethod ($b) {
    return function () {
      lexical $b;
      return $this->a * $b;
    };
  }
}

$e = new Example ();
$lambda = $e->myMethod (4);
var_dump ($lambda ()); // int(8)
$lambda2 = $e->myMethod (6);
var_dump ($lambda2 ()); // int(12)

So esentially, it does not matter whether you define a lambda function
inside a method or a function (or in global scope, for that matter), you
always use it the same way. The in-class-method lambda function only has
the additional advantage of being able to access the private and
protected class members since *internally* it is treated like a public
class method.

- Related to that, would it then be possible to add methods to a class at runtime using lambda functions as the added methods?

No.

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)?

If you want to add methods dynamically to classes, why not use the
runkit extension? I really don't see a point in making lambda functions
and closures something they are not.

Regards,
Christiaan


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

Reply via email to