rix
rix

Reputation: 10642

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

Upvotes: 4

Views: 2016

Answers (2)

salathe
salathe

Reputation: 51970

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');
}

Upvotes: 12

tim
tim

Reputation: 10186

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 :)

Upvotes: -3

Related Questions