您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

PHP构造函数返回NULL

PHP构造函数返回NULL

假设您使用的是PHP 5,则可以在构造函数中引发异常:

class NotFoundException extends Exception {}

class User {
    public function __construct($id) {
        if (!$this->loadById($id)) {
             throw new NotFoundException();
        }
    }
}

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false) {
    try {
        $this->LoggedUser = new User($_SESSION['verbiste_user']);
    } catch (NotFoundException $e) {}
}

为了清楚起见,您可以将其包装在静态工厂方法中:

class User {
    public static function load($id) {
        try {
            return new User($id);
        } catch (NotFoundException $unfe) {
            return null;
        }
    }
    // class body here...
}

$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
    $this->LoggedUser = User::load($_SESSION['verbiste_user']);

顺便说一句,某些版本的PHP 4允许您在构造函数中将$ this设置为NULL,但我认为这从未得到正式批准,并且最终删除了“功能”。

php 2022/1/1 18:15:17 有476人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶