简体   繁体   中英

Ternary operator syntax (PHP)

Just been learning about the ternary operator and was expecting the following to work:

$dbh =new PDO('mysql:blad','user','pass');
(!$dbh) ? throw new Exception('Error connecting to database'); : return $dbh; 

Instead i get the following error:

parse error: syntax error, unexpected T_THROW in...

Any ideas for the correct syntax?

Thank you

The syntax for the ternary operator is expr1 ? expr2 : expr3 expr1 ? expr2 : expr3 . An expression, put concisely, is "anything that has a value" .

For PHP versions prior to PHP 8, throw … and return … are not expressions, they are statements. This means they cannot be used as operands for a ternary operation.

As of PHP 8, throw ... is an expression, and so can be used as an operand for a ternary operation, and return ... remains a statement.


In any case, the PDO class throws its own exception if there is a problem in the constructor. The correct (meaning, non-broken) syntax would be like:

try {
    $dbh = new PDO('mysql:blad','user','pass');
    return $dbh;
} catch (PDOException $e) {
    throw new Exception('Error connecting to database');
}

Perhaps withouth the semicolon because the ternary operator in complete is seen as one command which you must end with a semicolon:

(!$dbh) ? throw new Exception('Error connecting to database') : return $dbh;  

so DONT end the command somewhere inbetween :)

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