0

我试图从 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.
4

3 回答 3

2

不,除了 PHP 中的“对所有事物都可见”之外,您实际上不能拥有任何类型的类可见性。您可以使用人们告诉您的各种技巧来部分近似它,但它们是毫无意义的浪费时间,因为它们无法强制执行可见性约束(如果程序员想要违反您的伪约束,所有这些都会受到微不足道的解决方法) ,如果没有强制执行,您也可以在程序员级别实现它(即,如果您认为不应该这样做,请不要这样做)。

如果您担心使用非常有限的异常类污染全局类名称空间(这将是我为您鼓掌的一个有效问题),这就是名称空间的用途;一个典型的专业 PHP 5.3 架构会将您的类作为YourApp\Email\SubscribeYourApp\Email\InvalidAddressException. (顺便说一句,这允许内部代码在不需要语句或完整命名空间规范的情况下Subscribe抛出 a 。)new InvalidAddressExceptionuse

于 2012-07-08T02:42:17.523 回答
1

我认为你最好的选择是使用依赖注入http://en.wikipedia.org/wiki/Dependency_injection。它有点先进,但我认为从长远来看它会有所帮助..

本质上,您可以使用获取所需数据的方法创建一个通用接口,并使异常类的构造函数具有接口类型的参数。然后让订阅类实现接口,这将允许将其传递给异常的构造函数。

您也可以直接将订阅对象作为参数传递给异常类的构造函数,并绕过接口使用。但是,该接口允许您让多个类都使用该接口和那些常用方法,如果您使用该模式,它们都可以构造您的异常类。而且您还将知道如何与这些类进行交互,因为它们使用相同的通用设计。

这并不能完全阻止您从类外部和脚本中构造异常,但是您将需要首先构造实现接口的类(或仅构造类本身,取决于您采用的方式),这是限制行为的好方法。

于 2012-07-08T02:30:26.923 回答
-1

这是一个想法。

使用define 设置一个“全球化”变量。

因此,在您的订阅类 __construct 函数中设置一个变量define( 'IN_USE', 1 );,然后如果/当调用 InvalidEmailException 时只需检查:

if( !IN_USE ) { exit; }
于 2012-07-08T02:33:05.983 回答