PHP构造函数返回一个NULL [英] PHP constructor to return a NULL
本文介绍了PHP构造函数返回一个NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码。一个 User
对象构造函数可能会失败,因此 $ this-> LoggedUser
c $ c> NULL 值,并在构造函数返回后释放对象?
I have this code. Is it possible for a User
object constructor to somehow fail so that $this->LoggedUser
is assigned a NULL
value and the object is freed after constructor returns?
$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
$this->LoggedUser = new User($_SESSION['verbiste_user']);
推荐答案
假设你使用PHP 5,构造函数中的异常:
Assuming you're using PHP 5, you can throw an exception in the constructor:
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) {}
}
你可以将它包装在一个静态的工厂方法中:
For clarity, you could wrap this in a static factory method:
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,我认为从来没有正式批准,特色最终被删除。
As an aside, some versions of PHP 4 allowed you to set $this to NULL inside the constructor but I don't think was ever officially sanctioned and the 'feature' was eventually removed.
这篇关于PHP构造函数返回一个NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文