I'm trying to have a child class from the Exception class just to handle errors and emit the proper error message given the error code. I changed my original code and made it more simple just to illustrate my problem.
Maybe it's not possible, but I don't want the InvalidEmailException class to be instantiated by the script. I just want it to be used by the Subscribe class if it's necessary (errors are found). Why would I want to do this anyway? Doesn't matter I'm just trying to understand how classes work.
/* Child class from the parent Exception class to handle errors
* pertinent to users being subscribed
*/
class InvalidEmailException extends Exception{
private $error_code;
private $email;
function __construct($error_code, $email){
$this->error_code = $error_code;
$this->email = $email;
$this->notifyUser();
}
function notifyUser(){
if($this->error_code == 2):
echo "<p>Invalid email: <em>{$this->email}</em></p>";
endif;
}
}
// Initial class to subscribe a user with the try catch checks
class Subscribe{
private $email;
private $error_code = 0;
function __construct($email){
$this->email = $email;
$this->validateEmail();
}
private function validateEmail(){
try{
if($this->email == ''):
throw new Exception('<p>Error: empty email address.</p>');
else:
if($this->email == 'invalid test'){
$this->error_code = 2;
throw new InvalidEmailException($this->error_code, $this->email);
}elseif($this->error_code == 0){
// Go to method to subscribe a user if the error code remains zero
$this->subscribeUser();
}
endif;
}catch(Exception $e){
echo $e->getMessage();
}
}
private function subscribeUser(){
echo $this->email.' added to the database!';
}
}
/*
* Script to use the Subscribe class, which would call
* the InvalidEmailException class if needed
*/
$email = 'invalid test'; // This could later on be used through the $_POST array to take an email from a form
$subscribe = new Subscribe($email); // Works well.
$test = new InvalidEmailException('2', 'a@b.c'); // Also works. I want this to throw an error.