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.
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? .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.