0

The variable $user is null in this closure function. I don't understand why.

Routes.php

require_once(__DIR__ . '/classes/user.php');
$user = User::getInstance(); // returns a $_SESSION user or a new User()

This does not work

$app->group('/user', function () use ($app, $user) {

    $app->post('/activate', function(Request $request, Response $response) {
        $parsedBody = $request->getParsedBody();
        $result = $user->activate($parsedBody); // error user is null
        return $response->withJson($result);
    });
});

This does

$app->group('/user', function () use ($app) {

    $app->post('/activate', function(Request $request, Response $response) {
        $parsedBody = $request->getParsedBody();
        $user = User::getInstance();
        $result = $user->activate($parsedBody);
        return $response->withJson($result);
    });
});
jozenbasin
  • 2,142
  • 2
  • 14
  • 22

1 Answers1

1

You need to inherit that variable into your function.

http://php.net/manual/en/functions.anonymous.php - #3

$app->group('/user', function () use ($app, $user) {

    $app->post('/activate', function(Request $request, Response $response) use ($user) {
        $parsedBody = $request->getParsedBody();
        $result = $user->activate($parsedBody); // now it shouldn't
        return $response->withJson($result);
    });
});
Mateusz Sip
  • 1,280
  • 1
  • 11
  • 11