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
. 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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With