Allenph
Allenph

Reputation: 2015

How to pass class instance scope to callback function?

I'm in the process of rewriting an MVC framework I've written. I've decided to incorporate explicit routing in addition to my framework's default routing behavior, but I'm having an issue.

This is the method that executed a route (It's a method on the App class)...

private function executeRoute($requestType, $route, $callback)
    {
      if (is_array($requestType))
      {
        if (in_array($_SERVER['REQUEST_METHOD'], $requestType))
          $matched = true;
        else
          $matched = false;
      }
      else if (($_SERVER['REQUEST_METHOD'] == $requestType) || ($requestType == "ALL"))
        $matched = true;
      else
        $matched = false;
      if ($matched)
      {
        $uriVariables = $this->getUriVariables($route, implode("/", $this->uri));
        if (is_array($uriVariables))
          call_user_func_array($callback, $uriVariables);
      }
    }

Here's where I'm having trouble...

$app = new App;

  $app->all("/", function() {
    $controller = $app->setController("test");
    if ($controller)
    {
      $app->controller->index();
    }
    else
      echo $controller;
  });

This isn't working because the callback function has it's own scope that doesn't contain the instance of my App class. Is there a way to pass a reference to the callback function without the developer explicitly adding his App instance as a dependency/argument to the callback function?

I would like to be able to use $app inside of the callback, or rewrite $this to a reference to the App instance.

Upvotes: 0

Views: 59

Answers (1)

Ihor Burlachenko
Ihor Burlachenko

Reputation: 4905

You need to use use to inherit variables from the parent scope.

$app = new App;

$app->all("/", function() use ($app) {
    $controller = $app->setController("test");
    if ($controller)
    {
        $app->controller->index();
    }
    else
        echo $controller;
});

Upvotes: 2

Related Questions