1

Ideally I would like to bind a statically declared closure to an object instance. But this has been asked and seems not to be possible?

Failing that, I would like to determine if a closure is statically defined or not, to know if I can bindTo() or not.... For example:

Class A {
  public function runClosure($closure) {
    #this is what I would like to do...
    if (! $closure->isStatic()) {
      $closure->bindTo($this, $this);
      return $closure();
    } else {
      return $closure($this);
    }
  }
}

Obviously, this example leaves out everything that would make this useful, but it illustrates the concept.

It would be great if there were some way to coerce a statically declared closure to bind to an object instance, though....

========== Edit ========= Why I want it? Okay, I'm building a new PHP MVC/ORM framework. My BaseController class has a "ProcessPost" method, which processes and validates the Posted data, then by default binds the data to the associated ORM object. But forms have other uses than just updating tables, so an option to ProcessPost (or the Form Array) is a "callable", which can be called for custom processing of the posted form data after Validation is performed. This can be any callable, including a closure, but in some cases a closure might want access to the member properties of the controller, in which case it should bindTo "this". One work-around is to have another parameter which specifies "bindTo" or not, but that's unattractive. Just seemed like their ought to be some way of testing "is_bindable($myClosure)" would be reasonable to expect.

ChrisNY
  • 3,917
  • 4
  • 27
  • 31
  • If you explain how this would be useful, maybe we could come with another way to achieve the desired effect? – Borislav Sabev Sep 09 '14 at 08:36
  • I have the same problem, with a use case: prototypical inheritance in php. I want to be able to do: `$object->f = function() { return $this->v; }` This works if you are in an object scope when defining `$object->f`, but not if you are in static scope. (if you add some magic in $object's class ). However there seems to be no way to determine if the closure is static or bound to an object. If you try to bind a static closure, php will trigger an error... See: https://github.com/Ariadne-CMS/arc-base/blob/master/src/lambda/Prototype.php – Auke Nov 27 '14 at 12:31

0 Answers0