Short String Syntax Script Syntax (PHP)

Just found out about the abbreviated ternary operator and was expecting the following:

$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 right syntax?

thanks

+4
source share
2 answers

Syntax for ternary operator expr1 ? expr2 : expr3 expr1 ? expr2 : expr3 . The expression, briefly expressed, is "all that matters . "

throw…; and return…; are not expressions; they are operators.


In any case, the PDO class throws its own exception if there is a problem in the constructor. The correct (i.e., not broken) syntax will look like this:

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

Perhaps with a semicolon, because the triple operator in its entirety is considered as one command, which you should end with a semicolon:

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

therefore DONT completes the command somewhere in between :)

-1
source

Source: https://habr.com/ru/post/1390624/


All Articles