简体   繁体   English

try-catch 块 php 中的变量范围

[英]Variable Scope in try-catch block php

I have the following code to determine if a new session should be created based on login information;我有以下代码来确定是否应根据登录信息创建新会话;

try {
    $_session = new \Proactivve\User\Sessions($_user);
    $start_session = $_session->startSession();
}
catch (\Proactivve\Exceptions\ProactivveAuthenticationException $e) {
    if($start_session === true) {
        // Successful login
        return array(/* ... */);
    }
    return array(/* ... */);
}

wherein I need to check the returned value of $start_session from the try block;其中我需要检查来自 try 块的$start_session的返回值; however, I am getting an "Undefined variable" error from PHP (v5.6.11) for the variable.但是,我从 PHP (v5.6.11) 收到该"Undefined variable""Undefined variable"错误。 I always thought that variables in PHP were scoped to the file, method or function, not to a block.我一直认为 PHP 中的变量范围是文件、方法或函数,而不是块。 Why am I receiving this error when the variable should be accessible?当变量应该可以访问时,为什么我会收到此错误?

The reason I am checking for a successful login within the AuthenticationException exception catcher is that when creating a new instance of the \\Proactivve\\User\\Sessions class, I check for an existing session and throw the authentication exception if one is not found, thus I need to check inside of this catch block to determine that the user is not already logged in.我在AuthenticationException异常捕获器中检查成功登录的原因是,在创建\\Proactivve\\User\\Sessions类的新实例时,我检查现有会话并在未找到时抛出身份验证异常,因此我需要检查此 catch 块的内部以确定用户尚未登录。

UPDATE:更新:

try {
    $_session = new \Proactivve\User\Sessions($_user);
}
catch (\Proactivve\Exceptions\ProactivveAuthenticationException $e) {
    if($_session->startSession() === true) {
        // Successful login
        return array(/* ... */);
    }
    return array(/* ... */);
}

This new method understands that after an exception is thrown, PHP stops executing the code in the try block and starts the session in the catch block;这个新方法明白,在抛出异常后,PHP停止执行try块中的代码,并在catch块中启动会话; however, now I receive Undefined variable: _session as the error.但是,现在我收到Undefined variable: _session作为错误。

If \\Proactivve\\User\\Sessions() is throwing an exception, then none of the other code in the try block is executed.如果\\Proactivve\\User\\Sessions()抛出异常,则不会执行try块中的任何其他代码。 Nothing will be assigned to $_session , and the following line is going to be skipped entirely.不会为$_session分配任何$_session ,并且将完全跳过以下行。

Scoping is not your problem, the problem is that the variables are never created.范围不是你的问题,问题是变量永远不会被创建。 If you need specific values in the catch block, you need to create them in a context where they cannot be interrupted by an exception.如果您需要catch块中的特定值,则需要在它们不能被异常中断的上下文中创建它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM