我只是创建一个从PDO封装的类。我想从我的新类中得到的东西是包装Try和Catch每个方法以捕获错误。但是,似乎try catch不在类内部执行。
class aegis{
private $init, $dsn, $user, $pass;
private $options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
];
public function __construct($host, $port, $db_name, $user, $pass){
$this->dsn = 'mysql:host='.$host.';port='.$port.';dbname='.$db_name;
$this->user = $user;
$this->pass = $pass;
$this->connect();
}
private function connect(){
$this->init = new PDO($this->dsn, $this->user, $this->pass, $this->options);
}
public function select($sqlStatement = NULL){
if($sqlStatement !== NULL){ $this->init->query($sqlStatement); }
}
public function insert($sqlStatement = NULL){
if($sqlStatement !== NULL){ $this->init->query($sqlStatement); }
}
public function logError(){
try{
$this->__construct();
$this->select();
$this->insert();
}catch(PDOException $e){
$error;
array_push($error, $e->getCode());
array_push($error, $e->getMessage());
return $error;
}
}
}
示例用法:
$aegis = new aegis($credential);
$error = $aegis->logError();
echo '<pre>';
print_r($error);
echo '<pre>';