【发布时间】:2012-07-07 23:09:57
【问题描述】:
我试图从 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.
【问题讨论】:
-
你如何加载类?有超载还是显式包含?
-
我打算稍后使用自动加载功能。这只是一个例子。请原谅我的无知,但了解我如何加载类很重要?
-
您尝试在编程中模拟友谊或组装事物(即某些类/功能仅可用于某些其他功能/类)。这可以在 PHP 中借助加载类的方式在一定程度上实现。
-
我想我可能明白你在说什么。因此,如果我将 InvalidEmailException 和订阅类放在单独的文件中,并通过订阅类文件显式包含 InvalidEmailException 类,那么 InvalidEmailException 类将无法通过脚本实例化(如我来自问题的php代码)。请帮我解决这个问题,这是我能做到的唯一方法吗?
-
如果你将它包含在类中,它可能会这样工作,是的,测试它
标签: php class exception exception-handling instantiation