PHP try catch:在try中定义变量

时间:2013-07-26 08:04:11

标签: php try-catch scope

我正在尝试调试一些代码。我希望能够在try中显示catch中定义的变量。例如变量$siteId

<?php
try {
    $siteId = 3;
    if(1 !== 2) {
        throw new Exception('1 does not equal 2!');
    }
} catch(Exception $e) {
    $moreInfo = '';
    if(isset($siteId)) {
        $moreInfo .= ' SiteId»' . $siteId;
    }
    echo 'Error' . $moreInfo . ':' . $e->getMessage();
}
?>

我得到的回复是Error: 1 does not equal 2!,而不是Error SiteId»3: 1 does not equal 2!。我做错了什么?

7 个答案:

答案 0 :(得分:7)

在try / catch构造之外声明$ siteId并在catch中使用!empty($siteId)

$siteId = null;
try {

}catch(Exceptions $e) {
  if( ! empty($siteId) ) {

  }
}

答案 1 :(得分:6)

PHP中的变量的范围是文件,方法或函数,(参见http://php.net/manual/en/language.variables.scope.php),所以我不确定这对你不起作用。快速切入PhpStorm可以为我输出正确的响应。

答案 2 :(得分:1)

尝试将\添加到Exception课程。所以你的代码变成了:

<?php
try {
    $siteId = 3;
    if(1 !== 2) {
        throw new \Exception('1 does not equal 2!');
    }
} catch(\Exception $e) {
    $moreInfo = '';
    if(isset($siteId)) {
        $moreInfo .= ' SiteId»' . $siteId;
    }
    echo 'Error' . $moreInfo . ':' . $e->getMessage();
}
?>

答案 3 :(得分:0)

尝试从try / catch移出$ siteId:

<?php
$siteId = 3;
try {        
    if(1 !== 2) {
        throw new Exception('1 does not equal 2!');
    }
} catch(Exception $e) {
    $moreInfo = '';
    if(isset($siteId)) {
        $moreInfo .= ' SiteId»' . $siteId;
    }
    echo 'Error' . $moreInfo . ':' . $e->getMessage();
}
?>

答案 4 :(得分:0)

我正在使用PHP 7.2,在我的情况下,在catch块中定义的变量在catch中不可用,所以这是一个解决方法:

protected $var;

try  {

 $var = 'Hello World';

 // Saving var in an external variable so it can be accessed by Catch
 $this->var = $var;

 throw new Exception("Error Processing Request", 1);

} catch (Exception $e) {

   var_dump($var); // null
   var_dump($this->var); // 'Hello World'

}

答案 5 :(得分:0)

<?php
$siteId = 3;
try {

    if(1 !== 2) {
        throw new Exception('1 does not equal 2!');
    }
} catch(Exception $e) {
    $moreInfo = '';
    if(!empty($siteId)) {
        $moreInfo .= ' SiteId»' . $siteId;
    }
    echo 'Error' . $moreInfo . ':' . $e->getMessage();
}
?>

答案 6 :(得分:-1)

我在php7中遇到了同样的问题,并且以某种方式对我有用

class dbConfig {
    private $servername ; private $username; private $password; private $conn;

     public function __construct()
    {
        $this->connect();
    }
    public function connect()
    {
        $servername = 'localhost';
        $username = 'root';
        $password= '';
        $dbName = 'dbname';
        try {
            $conn = new PDO("mysql:host=$servername;dbname=$dbName", $username, $password);
            // set the PDO error mode to exception
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo "Connected successfully"; 
            }
        catch(PDOException $e)
            {
            echo "Connection failed: " . $e->getMessage();
            }
    }