有什么问题或者抛出新的例外?

时间:2013-02-01 06:26:47

标签: php exception throw parse-error

我在public function __construct()的{​​{1}}内使用此代码:

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_HOSTBASE_DB_USER已定义。我收到以下错误:

  

解析错误:语法错误, / home /...中的意外T_THROW 6

我是否不允许将BASE_DB_PASS构造用于例外?我该如何解决这个问题?

2 个答案:

答案 0 :(得分:8)

尝试使用这样的方式让我知道它是否适合你 -

<?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();
?>

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

答案 1 :(得分:0)

另一种方法是在or逻辑运算符之后的匿名函数中抛出异常。

$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."); });