Assuming you are 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 can wrap this with a static factory method:
class User { public static function load($id) { try { return new User($id); } catch (NotFoundException $unfe) { return null; } }
As an aside, some versions of PHP 4 allowed you to set $ this to NULL inside the constructor, but I donβt think it was officially authorized, and the βfunctionβ was eventually removed.
jaz303 Feb 06 '10 at 21:23 2010-02-06 21:23
source share