50 php error-handling null constructor
我有这个代码.是否有可能User对象构造函数以某种方式失败,因此$this->LoggedUser分配了一个NULL值,并在构造函数返回后释放对象?
$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
$this->LoggedUser = new User($_SESSION['verbiste_user']);
Run Code Online (Sandbox Code Playgroud)
小智 66
假设您使用的是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) {}
}
Run Code Online (Sandbox Code Playgroud)
为清楚起见,您可以将其包装在静态工厂方法中:
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']);
Run Code Online (Sandbox Code Playgroud)
顺便说一下,PHP 4的某些版本允许你在构造函数中将$ this设置为NULL,但我认为没有正式批准,并且最终删除了'feature'.
Pek*_*ica 12
AFAIK这个无法做到,new总会返回一个对象的实例.
我通常做的解决方法是:
向->valid对象添加布尔标志,以确定对象是否已成功加载.然后构造函数将设置标志
创建执行new命令的包装器函数,成功时返回新对象,或者在失败时销毁它并返回false
-
function get_car($model)
{
$car = new Car($model);
if ($car->valid === true) return $car; else return false;
}
Run Code Online (Sandbox Code Playgroud)
我有兴趣听听替代方法,但我不知道.
以这种方式考虑它.使用时new,会得到一个新对象.期.你正在做的是你有一个搜索现有用户的功能,并在找到时返回它.表达这一点的最好的方法可能是静态类函数,例如User :: findUser().当您从基类派生类时,这也是可扩展的.
小智 5
工厂在这里可能有用:
class UserFactory
{
static public function create( $id )
{
return (
filter_var(
$id,
FILTER_VALIDATE_INT,
[ 'options' => [ 'min_range' => 1, ] ]
)
? new User( $id )
: null
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34378 次 |
| 最近记录: |