PHP构造函数返回一个NULL

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

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

假设你使用PHP 5,你可以在构造函数中抛出一个exception:

 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,但是我不认为这是正式批准的,并且“特性”最终被删除。

AFAIK不能这样做, new将始终返回该对象的一个​​实例。

我通常做的是解决这个问题:

  • 向确定对象是否成功加载的对象添加->valid布尔标志。 构造函数将会设置标志

  • 创build一个执行new命令的包装函数,在成功时返回新的对象,或者在失败时破坏它并返回false

 function get_car($model) { $car = new Car($model); if ($car->valid === true) return $car; else return false; } 

我有兴趣了解其他方法,但我不知道。

考虑这样。 当你使用new ,你得到一个新的对象。 期。 你正在做的是你有一个function,search一个现有的用户,并返回它find。 expression这个最好的东西可能是一个静态类函数,如User :: findUser()。 当你从基类派生你的类时,这也是可扩展的。

在这里工厂可能是有用的:

 class UserFactory { static public function create( $id ) { return ( filter_var( $id, FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 1, ] ] ) ? new User( $id ) : null ); } } 

当构造函数由于某些未知原因而失败时,它不会返回NULL值或FALSE,但会引发exception。 与所有与PHP5一样。 如果你不处理这个exception,那么这个脚本将会停止执行,并带有一个Uncaught Exception错误。

也许是这样的:

 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