Search code examples
phpexceptionthrowparse-error

What's wrong with or throw new Exception?


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?


Solution

  • 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