简体   繁体   中英

When a break is reached in PHP how many levels does it break out of?

Ok this may be an elementary question, but I want an informed answer and I can't seem to get the keywords right to get an answer through google. If this is a duplicate please close it and point me in the right direction.

So here's the question. In the code below, when the break that's pointed to is executed, where does it break out too?

case 'changeEmployeeInfo':
    $con = db_connect(DBNAME, DBUSERNAME, DBPASSWORD , DBHOST);
    $query = 'UPDATE USERS SET firstname = ?, lastname = ?, email = ? where idusers = ?';
    $updateValues = array($firstName,$lastName,$email,$employeeID);
    $newID = db_change($query,$updateValues,$con);
    if($_SESSION['role']==1||$_SESSION['role']==3||$_SESSION['role']==4){
        if($_POST['status']== true){
            $status = 1;
        }elseif($_POST['status']==false){
            $status = 0;
        }
        else{
            break;//<--THIS IS THE BREAK I'M TALKING ABOUT
        }
        $query = 'UPDATE USERS SET status = ? where idusers = ?';
        $updateValues = array($status, $employeeID);
        $newID = db_change($query,$updateValues,$con);
    }
    db_disconnect($con);
    break;

My instinct tells me that the db_disconnect function will still be executed but the UPDATE USERS query and it's associated lines will not be. Am I correct in thinking this? Thanks!

break in PHP breaks exactly one level, in your case the case . To break more levels, use break n :

From the documentation :

$i = 0;
while (++$i) {
    switch ($i) {
    case 5:
        echo "At 5<br />\n";
        break 1;  /* Exit only the switch. */
    case 10:
        echo "At 10; quitting<br />\n";
        break 2;  /* Exit the switch and the while. */
    default:
        break;
    }
}

When a break is reached in PHP how many levels does it break out of?

1

In your example, break will move out to the switch level, leaving your case statement. db_disconnect will not be run.

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