我试图从 Exception 类中创建一个子类来处理错误并在给定错误代码的情况下发出正确的错误消息。我更改了原始代码并使其更简单,只是为了说明我的问题。
也许这是不可能的,但我不希望 InvalidEmailException 类被脚本实例化。如果有必要,我只希望订阅类使用它(发现错误)。我为什么要这样做呢?没关系,我只是想了解课程的运作方式。
/* 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.