如何将参数传递给匿名函数
How to pass parameter to anonymous function
我正在使用一个库来跟踪我们 PHP 应用程序中的错误。
我复制并粘贴了他们提供的有关如何初始化库的代码,并将其集成到我的 class __construct()
声明中:
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]);
});
}
}
}
现在我知道我总是可以将 $username
添加到会话中并从那里获取它,然后可能在初始化库后将其取消设置,但我宁愿不走那条路。在为库配置范围时如何将变量传递给匿名函数?
我通过以下方式让它工作:
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]);
}
});
$x = 123;
Sentry\configureScope(function (Sentry\State\Scope $scope) use($x) : void {
// you may use $x
$scope->setUser(['username' => $_SESSION['username']]);
});
我正在使用一个库来跟踪我们 PHP 应用程序中的错误。
我复制并粘贴了他们提供的有关如何初始化库的代码,并将其集成到我的 class __construct()
声明中:
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]);
});
}
}
}
现在我知道我总是可以将 $username
添加到会话中并从那里获取它,然后可能在初始化库后将其取消设置,但我宁愿不走那条路。在为库配置范围时如何将变量传递给匿名函数?
我通过以下方式让它工作:
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]);
}
});
$x = 123;
Sentry\configureScope(function (Sentry\State\Scope $scope) use($x) : void {
// you may use $x
$scope->setUser(['username' => $_SESSION['username']]);
});