简体   繁体   中英

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; however, I am getting an "Undefined variable" error from PHP (v5.6.11) for the variable. I always thought that variables in PHP were scoped to the file, method or function, not to a block. 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.

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; however, now I receive Undefined variable: _session as the error.

If \\Proactivve\\User\\Sessions() is throwing an exception, then none of the other code in the try block is executed. Nothing will be assigned to $_session , and the following line is going to be skipped entirely.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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