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);
    });
});
1

1 Answer 1

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);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Ah.. I really hate that. Is there any way to do it less strict?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.