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 …andreturn …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, andreturn ...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: