Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP try catch: get variable defined in try

Tags:

I'm trying to debug some code. I want to be able to show variables defined in try in catch. For example the variable $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();
}
?>

The response I get is Error: 1 does not equal 2! instead of Error SiteId»3: 1 does not equal 2!. What am I doing wrong?

like image 762
iDev247 Avatar asked Jul 26 '13 08:07

iDev247


2 Answers

Declare $siteId outside the try/catch construct and use !empty($siteId) inside the catch.

$siteId = null;
try {

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

  }
}
like image 126
mgrueter Avatar answered Sep 22 '22 17:09

mgrueter


Variables in PHP are scoped to the file, method or function, (see http://php.net/manual/en/language.variables.scope.php), so I'm not sure how this isn't working for you. A quick cut-n-paste into PhpStorm outputs the correct response for me.

like image 39
ben3000 Avatar answered Sep 18 '22 17:09

ben3000