0

Is it possible to create single instance of the class, which will be used in all routes. For example I have this code:

$app = new \Slim\Slim([
        'mode'  => 'development',
        'debug' => true
    ]);
    use App\API;

    $API = new API;

$app->get('/', function () {

    $API->insertMessage();
});

$app->run();

At the moment this is not working, I need to put $API = new API inside get request.

Sasha
  • 8,521
  • 23
  • 91
  • 174

1 Answers1

1

Yes, it is possible.

You're looking for another (and different) use statement:

$app->get('/', function () use ($API) {
                           ##########    
    $API->insertMessage();
});

That should do it for you, it is inheriting variables from the parent scope. See as well: Anonymous functions (PHP Manual) and In PHP 5.3.0, what is the function “use” identifier?.

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • Yep, this is working. I wanted something more global (only one call) but this will do :). Thanks :) – Sasha Dec 22 '14 at 16:03
  • This is only one call and if I see your code right, `$API` is in the global scope, too. – hakre Dec 22 '14 at 16:05