As I understand it, the purpose and benefit would be that this will allow me to have custom functions triggered by the exception in conjunction with my custom message. So, if I'm misunderstanding the purpose then I need to understand it before trying to use it.
I started with the example here http://php.net/manual/en/language.excep ... ending.php but couldn't figure out how to separate it out into separate class files and a script file.
Then someone on the other forum gave me examples here, http://www.webdeveloper.com/forum/showt ... ost1171036 and I'm still having trouble with it. Even if I figure out the code from the other forum, I'm wondering what is the purpose of all the other code in the example at php.net.
I am trying to apply this concept to a database class and use it for making the connection to the database. Now this may not be the right use of it but I feel like if I can use it for something I'm working on then I will understand it well enough to apply it in situations where it is called for.
Here are the 4 files of code I have now. They are way off from the example at php.net which may be part of the reason for my confusion. I need some help figuring out how to apply the example from php.net to my database scenario.
Code: Select all
class_customException.php
<?php
abstract class customException extends Exception{
/**
* This method must be defined in each sub-class
* @return string Message to be output by exception handler
*/
//comented this line out and it made no difference
//tried putting some code in it and get error
public abstract function custom();
/**
* The callback function for set_exception_handler()
*/
public static function handler($e) {
if(is_a($e, 'customException')) {
user_error($e->custom());
}
else {
user_error($e->message);
}
}
}
?>
class_ehandler_db.php
******************************************************************************
<?php
require_once('class_customException.php');
class ehandler_db extends customException{
public function custom()
{
return ("Hey! You can't do that! Stop it!<br />\nERROR: " . $this->message);
}
}
?>
class_db.php
********************************************************************************
<?php
include('../includes/config.inc.php');
require_once('class_ehandler_db.php');
class db{
function init_con(){
//initiate the connection
//using constants from config file
try{
$con = mysql_connect(DB_HOST, 'DB_USER', DB_PASS);
if(!$con){
throw new ehandler_db("Unable to connect to database. This is a test.");
}
else{
echo "Connection Successful";
}
}
catch (Exception $e){
echo "Exception Caught: " . $e->getMessage();
}
}
}
?>
testing.php
************************************************************************************
<?php
//testing db exception handling
//error_reporting(0);
require_once('class_db.php');
set_exception_handler(array('customException', 'handler'));
$dbcon = new db();
$dbcon->init_con();
?>