Supponendo che si sta utilizzando PHP 5, è possibile generare un'eccezione nel costruttore:
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) {}
}
Per chiarezza, si potrebbe avvolgere questo in un statica metodo factory:
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']);
per inciso, alcune versioni di PHP 4 ha permesso di impostare $ questo per NUL L all'interno del costruttore, ma non credo sia mai stato ufficialmente sanzionato e la "feature" è stata rimossa.
Grande prima domanda a proposito. –
Ho visto un certo CMS popolare che restituisce FALSE in un costruttore. Cosa succede con quello?!?! – loungerdork
Ho pensato di entrare qui per motivi di documentazione. Poiché la data è così indietro, è possibile che il CMS che stai vedendo sia stato creato per PHP4. PHP4 permetteva un sacco di cose cattive, non ultima delle quali permetteva all'utente di sovrascrivere $ nel costruttore chiamato (ad esempio $ this = false). – techdude