返回 NULL 的 PHP 构造函数

标签 php constructor error-handling null

我有这个代码。 User 对象构造函数是否可能以某种方式失败,以便为 $this->LoggedUser 分配一个 NULL 值并在之后释放该对象构造函数返回?

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

最佳答案

假设您使用的是 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,但我认为从未得到正式批准,并且最终删除了“功能”。

关于返回 NULL 的 PHP 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2214724/

相关文章:

java - 如何设计构造函数?

java - 用接受字符串参数的构造函数实例化一个类对象?

java - 多个错误代码配置 web.xml

testing - Fortran运行时错误: Bad value during integer read

json - 在 Azure 数据工厂中读取变量 JSON 时出现问题

php - PHP 中的 oci_connect 空白页

javascript - html <输入需要包含特定文本

php - 定位 WooCommerce 类别的高级自定义字段

javascript - 将 jquery 应用于加载到 div 的页面

c++ - C++ 中包装器类的大小写相关可变性(例如 uint8_t 数组包装器)