我有这个代码。 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/