PHP try catch: get the variable defined in try

I am trying to debug some code. I want to show the 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 answer I get is Error: 1 does not equal 2! instead of Error SiteId»3: 1 does not equal 2! . What am I doing wrong?

+11
source share
6 answers

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

 $siteId = null; try { }catch(Exceptions $e) { if( ! empty($siteId) ) { } } 
+7
source

Variables in PHP are attached to a file, method or function (see http://php.net/manual/en/language.variables.scope.php ), so I'm not sure how this does not work for you. The quick cut-n-paste in PhpStorm prints the correct answer for me.

+6
source

Try adding \ to the Exception class. So your code becomes:

 <?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(); } ?> 
+1
source

try to get $ siteId out of try / catch:

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

I am using PHP 7.2, in my case the variable defined inside the Try block is not available inside catch, so there is a workaround here:

 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' } 
0
source

I ran into the same problem in php7 and somehow this work for me

 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(); } } 
0
source

Source: https://habr.com/ru/post/950335/


All Articles