Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary operator syntax (PHP)

Tags:

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

like image 723
rix Avatar asked Jan 17 '23 19:01

rix


1 Answers

The syntax for the ternary operator is 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');
}
like image 61
salathe Avatar answered Feb 15 '23 22:02

salathe