PHP工厂,用于在验证后返回条件对象


PHP factory for returning conditional objects after verification?

我基本上需要从PHP类中调用两个构造函数中的一个,这取决于是否需要验证。

我当前的代码如下:

class Event extends Generic {
    private $user_id;
    function __construct($user_id=null) {
        $this->user_id = $user_id;
    }
    public function verify($user_id=null, $identifier=null) {
        if (parent::verifyUser($user_id, $identifier)) {
            return new Event($user_id);
        }
        else {
            // what gets retruend here in the event of a failure???
        }
    }
    public function noverify($user_id=null) {
        return new Event(user_id);
    }
}

这样调用代码:

$event = new Event();
$obj1 = $event->noverify(5);
$obj2 = $event->verify(5, 100);

如果构造函数内部的条件失败,我真的不清楚该如何处理构造函数失败的事件。我是不是走错了路?

我要么抛出异常,要么返回FALSE:

else {
    throw new Exception('verification failed');
}

else {
    return FALSE;
}