Home > Net >  How to pass parameter to anonymous function
How to pass parameter to anonymous function

Time:03-18

I am using a library to track errors in our PHP application.

I copied and pasted a code they provided on how to initialize the library and integrated that on my class __construct() declaration:

function __construct($username = null) {
    parent::__construct();

    if(SENTRY === true) {
        if(!empty($username)) {
            Sentry\configureScope(function (Sentry\State\Scope $scope): void {
                $scope->setUser(['username' => $username]);
            });
        } else if(!empty($_SESSION['username'])) {
            Sentry\configureScope(function (Sentry\State\Scope $scope): void {
                $scope->setUser(['username' => $_SESSION['username']]);
            });
        } else {
            Sentry\configureScope(function (Sentry\State\Scope $scope): void {
                $scope->setUser(['username' => null]);
            });
        }
    }
}

Now I know I could always add the $username to the session and grab it from there and then maybe unset it after initializing the library but I'd rather not go that route. How do I pass the variable to the anonymous function when configuring the scope for the library?

CodePudding user response:

I got it to work by doing:

Sentry\configureScope(function (Sentry\State\Scope $scope) use ($username) : void {
    if(!empty($username)) {
        $scope->setUser(['username' => $username]);
    } else if(!empty($_SESSION['username'])) {
        $scope->setUser(['username' => $_SESSION['username']]);
    } else {
        $scope->setUser(['username' => null]);
    }
});

CodePudding user response:

$x = 123;
Sentry\configureScope(function (Sentry\State\Scope $scope) use($x) : void {
                // you may use $x
                $scope->setUser(['username' => $_SESSION['username']]);
            });
  • Related