PHP构造函数返回NULL
我有这个代码。 User对象构造函数是否有可能以某种方式失败,以便为$this->LoggedUser分配NULL值,并在构造函数返回后释放对象?
$this->LoggedUser = NULL;
if ($_SESSION['verbiste_user'] != false)
$this->LoggedUser = new User($_SESSION['verbiste_user']);
6个解决方案
66 votes
假设您使用的是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,但我认为从未正式批准过该功能,最终删除了“功能”。
jaz303 answered 2020-02-02T08:50:07Z
12 votes
不能执行此操作,new将始终返回该对象的实例。
为了解决这个问题,我通常要做的是:
向对象添加new布尔标志,以确定是否成功加载对象。 然后,构造函数将设置标志
创建一个执行new命令的包装函数,成功后返回新对象,否则失败则销毁并返回false
--
function get_car($model)
{
$car = new Car($model);
if ($car->valid === true) return $car; else return false;
}
我想听听有关替代方法的信息,但我什么都不知道。
Pekka 웃 answered 2020-02-02T08:50:50Z
5 votes
这样考虑吧。 当您使用new时,您将获得一个新对象。 期。 您正在做的是拥有一个搜索现有用户并在找到用户后将其返回的功能。 最好的表达方式可能是静态类函数,例如User :: findUser()。 当您从基类派生类时,这也可以扩展。
Wim answered 2020-02-02T08:51:10Z
4 votes
当构造函数由于某种未知原因而失败时,它不会返回NULL值或FALSE,但会引发异常。 与PHP5的所有内容一样。 如果您不处理异常,则脚本将停止执行,并显示“未捕获的异常”错误。
TheGrandWazoo answered 2020-02-02T08:51:30Z
4 votes
工厂可能在这里有用:
class UserFactory
{
static public function create( $id )
{
return (
filter_var(
$id,
FILTER_VALIDATE_INT,
[ 'options' => [ 'min_range' => 1, ] ]
)
? new User( $id )
: null
);
}
}
kaiser answered 2020-02-02T08:51:50Z
3 votes
也许是这样的:
class CantCreateException extends Exception{
}
class SomeClass {
public function __construct() {
if (something_bad_happens) {
throw ( new CantCreateException());
}
}
}
try{
$obj = new SomeClass();
}
catch(CantCreateException $e){
$obj = null;
}
if($obj===null) echo "couldn't create object";
//jaz303 stole my idea an wrap it into a static method
useless answered 2020-02-02T08:52:10Z