我正在尝试使用 try catch 块中的属性。try catch 块在类内部。我想扩展一个特定的类,使其成为处理异常的类的子类。问题是,当我尝试使用子类中的这些变量时,它总是说未定义。我必须删除这两个类才能捕获属性。通过在try catch块内部添加return语句(我添加了return 1)在此处阅读了其他一些答案后,它似乎不起作用,并且总是说未定义的变量。有什么帮助吗?
语言是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';
?>