What's wrong with or throw new Exception?
Asked Answered
P

2

11

I'm using this code inside the public function __construct() of a class:

$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or throw new Exception("Couldn't connect to database.");

BASE_DB_HOST, BASE_DB_USER and BASE_DB_PASS are defined. I get the following error:

Parse error: syntax error, unexpected T_THROW in /home/... on line 6

Am I not allowed to use the or construction with Exceptions? How can I workaround this?

Portugal answered 1/2, 2013 at 6:26 Comment(6)
$connection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or die("Couldn't connect to database.");Mahaffey
I want to use an exception. Is something similar possible? And why isn't this possible?Portugal
throw is a statement, or needs to be followed by an expression.Cadge
Don't use mysql_ functions, if you use pdo you get exceptions for free.Footboard
Closing this as "Too localized" makes no sense at all, this is quite commonFalconet
The resolution for this bug/feature req. was 'submit an RFC'. It's a deep change to have statements (like throw, return) mixed with expressions.Alurta
D
10

Try using like this and let me know if its work for you or not-

<?php
function throwException() {
    throw new Exception("Couldn't connect to database.");
}

$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) OR throwException();
?>

Reference - http://www.php.net/manual/en/language.exceptions.php#81960

Dulin answered 1/2, 2013 at 6:30 Comment(0)
C
0

Another way is to throw an exception in an anonymous function after the or logical operator.

$this->mConnection = mysql_connect(BASE_DB_HOST,BASE_DB_USER,BASE_DB_PASS) or call_user_func(function() { throw new Exception("Couldn't connect to database."); });
Coachwork answered 23/9, 2015 at 3:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.