我想在try catch塊內使用屬性。 try catch塊在類內。 我想擴展一個特定的類,使其成爲處理異常的類的子類。 問題是,當我嘗試從子類中使用這些變量時,它總是說未定義。我必須刪除兩個類才能捕獲屬性。通過在try catch塊內部添加一個return語句(我添加了return 1)之後,在閱讀了其他一些答案之後,它似乎不起作用,並且它始終表示未定義的變量。 有什麼幫助嗎?屬性不能在try catch塊外使用
語言是php
的源代碼沒有類作品完美:
try
{
//$pdo variable to insert PDO object information
$pdo = new PDO('mysql:host=localhost;dbname=studenti', 'root', '');
//Set php to catch exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Set UTF-8 for character encodings
$pdo->exec('SET NAMES "utf8"');
}
//Catch error if unable to connect
catch(PDOException $e)
{
//error variable
$error = 'Unable to connect with database. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
//Another Exception handling
try
{
//Select statement
$sql = 'SELECT * FROM dega';
$select = $pdo->query($sql);
}
catch(PDOException $e)
{
//error variable
$error = 'Unable to select table. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
的源代碼與類不起作用:
<?php
//PDO class, connection with MySQL database
class Connect
{
function connection()
{
$pdo = null;
try
{
//$pdo variable to insert PDO object information
$pdo = new PDO('mysql:host=localhost;dbname=studenti', 'root', '');
//Set php to catch exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Set UTF-8 for character encodings
$pdo->exec('SET NAMES "utf8"');
}
//Catch error if unable to connect
catch(PDOException $e)
{
//error variable
$error = 'Unable to connect with database. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
}
}
class Select extends Connect
{
function selection()
{
//Another Exception handling
try
{
//Select statement
$sql = 'SELECT * FROM dega';
$select = $pdo->query($sql);
}
catch(PDOException $e)
{
//error variable
$error = 'Unable to select table. ' . $e->getMessage();
//include file once and show on screen error message
include_once $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
//Exit and don't process further
exit();
}
}
}
//Output if successful
$error = 'Database connection established.';
include $_SERVER['DOCUMENT_ROOT'] . '/inc/error.inc.php';
?>
只是擴展,忘了添加它。 即使聲明瞭$ pdo,它仍然不起作用,它說未定義。我宣佈它爲空。 – GSquadron 2013-04-26 00:38:25
@GSquadron,請閱讀文檔。你可以從那裏獲得所有需要的信息。 – sectus 2013-04-26 00:44:01
您無法在文檔中找到如何調用try catch塊之外的屬性。我在此之前先修改了它。 – GSquadron 2013-04-26 01:01:34