PHP闭包中的变量为空

时间:2017-05-29 01:56:50

标签: php

此闭包函数中的变量$user为null。我不明白为什么。

routes.php文件

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

这不起作用

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

这样做

$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 个答案:

答案 0 :(得分:1)

您需要将该变量继承到您的函数中。

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