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?
Declare $siteId outside the try/catch construct and use !empty($siteId)
inside the catch.
$siteId = null;
try {
}catch(Exceptions $e) {
if( ! empty($siteId) ) {
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With