我想从Exception类的子类只处理错误,并给出错误代码发出适当的错误消息。为了说明我的问题,我更改了原始代码并使其更简单。PHP - 我可以创建一个不能通过另一个类实例化的类吗?
也许这是不可能的,但我不希望InvalidEmailException类被脚本实例化。如果有必要,我只是希望它可以被Subscribe类使用(发现错误)。无论如何,我为什么要这么做?无关紧要我只是想了解课程是如何运作的。
/* 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', '[email protected]'); // Also works. I want this to throw an error.
如何加载类?与outoload或明确包括? – 2012-07-08 01:44:52
我打算稍后使用自动加载功能。这只是一个例子。原谅我的无知,但了解我如何加载课程很重要? – 2012-07-08 01:48:00
你试图效仿编程中的友谊或集会thingy(我。即某些类别/功能仅可用于某些其他功能/类别)。这可以在PHP中获得一些帮助,如何加载类。 – 2012-07-08 01:51:51