php构造函数里抛出异常_php-在类的构造函数中返回值
php-在類的構造函數(shù)中返回值
到目前為止,我有一個帶有構造函數(shù)的29447791671682017201728類
public function __construct ($identifier = NULL)
{
// Return me.
if ( $identifier != NULL )
{
$this->emailAddress = $identifier;
if ($this->loadUser() )
return $this;
else
{
// registered user requested , but not found !
return false;
}
}
29447791671682017201728的功能是在數(shù)據(jù)庫中查找特定的電子郵件地址。當我將標識符設置為某些電子郵件時,我確定它不在數(shù)據(jù)庫中; 第一個IF被傳遞,并轉到第一個ELSE。 這里的構造函數(shù)應該返回FALSE; 但是,它返回具有所有NULL值的類的對象!
我該如何預防? 謝謝
編輯:
謝謝大家的回答。 那太快了! 我看到OOP的方式是拋出異常。 因此,我的問題改變了,我應該如何處理異常?php.net的手冊非常令人困惑!
// Setup the user ( we assume he is a user first. referees, admins are considered users too )
try { $him = new user ($_emailAddress);
} catch (Exception $e_u) {
// try the groups database
try { $him = new group ($_emailAddress);
} catch (Exception $e_g) {
// email address was not in any of them !!
}
}
8個解決方案
71 votes
構造函數(shù)不會獲得返回值。 它們完全用于實例化該類。
在不調(diào)整您已經(jīng)在做的事情的情況下,您可以考慮在此處使用異常。
public function __construct ($identifier = NULL)
{
$this->emailAddress = $identifier;
$this->loadUser();
}
private function loadUser ()
{
// try to load the user
if (/* not able to load user */) {
throw new Exception('Unable to load user using identifier: ' . $this->identifier);
}
}
現(xiàn)在,您可以以這種方式創(chuàng)建新用戶。
try {
$user = new User('user@example.com');
} catch (Exception $e) {
// unable to create the user using that id, handle the exception
}
erisco answered 2020-06-29T19:50:56Z
8 votes
構造函數(shù)假設要創(chuàng)建一個對象。 由于在php中,布爾值不被視為對象,因此唯一的選擇是null。 否則,請使用變通辦法,即編寫創(chuàng)建實際對象的靜態(tài)方法。
public static function CheckAndCreate($identifier){
$result = self::loadUser();
if($result === true){
return new EmailClassNameHere();
}else{
return false;
}
}
worenga answered 2020-06-29T19:51:16Z
7 votes
您能做的最好的就是史蒂夫的建議。除了將構造函數(shù)參數(shù)分配給對象屬性之外,不要創(chuàng)建執(zhí)行任何工作的構造函數(shù),不要創(chuàng)建一些默認參數(shù),而別無其他。構造函數(shù)旨在創(chuàng)建功能齊全的對象。此類對象在實例化后必須始終按預期工作。用戶具有電子郵件,姓名以及其他一些屬性。當您要實例化用戶對象時,請將所有這些屬性提供給其構造函數(shù)。拋出異常也不是一個好方法。在異常情況下應拋出異常。通過電子郵件詢問用戶并不是什么例外,即使您最終發(fā)現(xiàn)不存在這樣的用戶。例如,如果您通過email =”來請求用戶,則可能是例外(除非這是系統(tǒng)中的常規(guī)狀態(tài),但id則建議電子郵件在這些情況下為空)。要獲得用戶對象的所有這些屬性,您應該有一個工廠(或存儲庫,如果您愿意的話)對象(是的,一個對象-無論如何使用靜態(tài)方法都是不好的做法)私有構造函數(shù)也不是一個好習慣(無論如何,您都需要一個靜態(tài)方法,正如我已經(jīng)說過的,靜態(tài)函數(shù)非常糟糕)
所以結果應該是這樣的:
class User {
private $name;
private $email;
private $otherprop;
public function __construct($name, $email, $otherprop = null) {
$this->name = $name;
$this->email = $email;
$this->otherprop = $otherprop;
}
}
class UserRepository {
private $db;
public function __construct($db) {
$this->db = $db; //this is what constructors should only do
}
public function getUserByEmail($email) {
$sql = "SELECT * FROM users WHERE email = $email"; //do some quoting here
$data = $this->db->fetchOneRow($sql); //supose email is unique in the db
if($data) {
return new User($data['name'], $data['email'], $data['otherprop']);
} else {
return null;
}
}
}
$repository = new UserRepository($database); //suppose we have users stored in db
$user = $repository->getUserByEmail('whatever@wherever.com');
if($user === null) {
//show error or whatever you want to do in that case
} else {
//do the job with user object
}
看啊 沒有靜態(tài),沒有異常,簡單的構造函數(shù)以及非常易讀,可測試和可修改的
slepic answered 2020-06-29T19:51:47Z
3 votes
構造函數(shù)只能返回嘗試創(chuàng)建的對象,而不能返回任何東西。 如果實例化無法正確完成,您將發(fā)現(xiàn)一個擁有try/catch個屬性的類實例。
如果對象加載時處于不完整或錯誤狀態(tài),我建議設置一個屬性來表明這一點。
// error status property
public $error = NULL;
public function __construct ($identifier = NULL)
{
// Return me.
if ( $identifier != NULL )
{
$this->emailAddress = $identifier;
if (!$this->loadUser() )
{
// registered user requested , but not found !
$this->error = "user not found";
}
}
然后,在實例化對象時,可以檢查它是否具有錯誤狀態(tài):
$obj = new MyObject($identifier);
if (!empty($obj->error)) {
// something failed.
}
另一個(也許更好)的選擇是在構造函數(shù)中引發(fā)異常,并將實例化包裝在try/catch中。
Michael Berkowski answered 2020-06-29T19:52:21Z
2 votes
為什么不簡單地將結果傳遞給構建對象所需的構造函數(shù),而不是嘗試使構造函數(shù)有時失敗?
即使有時使它失敗,您仍然需要在調(diào)用構造函數(shù)之后進行檢查以確保它確實進行了構造,并且在這些行中,您只需調(diào)用-> loadUser()并將結果傳遞給構造函數(shù)即可。
有人告訴我,這是一個很好的提示:“總是向構造函數(shù)提供構建對象所需的內(nèi)容,而不是讓它去尋找它。”
public function __construct ($emailInTheDatabase, $otherFieldNeeded)
{
$this->emailAddress = $emailInTheDatabase;
$this->otherField = $otherFieldNeeded;
}
Steve answered 2020-06-29T19:52:50Z
0 votes
感謝您的所有評論和解決方案。 這是我為解決此問題所做的工作:(希望它對其他人有幫助)
// Setup the user ( we assume he is a user first. referees, admins are considered users too )
try {
$him = new user ($_emailAddress);
// check the supplied password
$pass_ok = $him->auth($_Password);
// check the activation status
$active_ok = $him->makeActive();
} catch (Exception $e_u) {
// try the groups database
try {
$him = new group ($_emailAddress);
// check the supplied password
$pass_ok = $him->auth($_Password);
//var_dump ($pass_ok);
// check the activation status
$active_ok = $him->makeActive();
} catch (Exception $e_g) {
// email address was not in any of them !!
$pass_ok = false; $active_ok = false;
}
}
Anoosh Ravan answered 2020-06-29T19:53:10Z
0 votes
我不會在結構中投入太多。 您應該考慮使用靜態(tài)函數(shù)來創(chuàng)建User(工廠),而不是將所有內(nèi)容都放在構造函數(shù)中。 因此,您仍然可以使用用戶對象,而不必隱式調(diào)用load函數(shù)。 這樣可以減輕您的痛苦。
public function __construct(){}
public function setIdentifier($value){
$this->identifier = $value;
}
public function load(){
// whatever you need to load here
//...
throw new UserParameterNotSetException('identifier not set');
// ...
// if user cannot be loaded properly
throw new UserNotFoundException('could not found user');
}
public static function loadUser($identifier){
$user = new User();
$user->setIdentifier($identifier);
$user->load();
return $user;
}
用法示例:
$user = new User();
try{
$user->setIdentifier('identifier');
$user->load();
}
catch(UserParameterNotSetException $e){
//...
}
catch(UserNotFoundException $e){
// do whatever you need to do when user is not found
}
// With the factory static function:
try{
$user2 = User::loadUser('identifier');
}
catch(UserParameterNotSetException $e){
//...
}
catch(UserNotFoundException $e){
// do whatever you need to do when user is not found
}
Nico answered 2020-06-29T19:53:34Z
0 votes
令我驚訝的是,四年來,沒有一個22k的觀看者建議創(chuàng)建私有構造函數(shù)和試圖創(chuàng)建這樣的對象的方法:
class A {
private function __construct () {
echo "Created!\n";
}
public static function attemptToCreate ($should_it_succeed) {
if ($should_it_succeed) {
return new A();
}
return false;
}
}
var_dump(A::attemptToCreate(0)); // bool(false)
var_dump(A::attemptToCreate(1)); // object(A)#1 (0) {}
//! new A(); - gives error
這樣,您將得到一個對象或false(也可以使它返回null)。 捕獲這兩種情況現(xiàn)在非常容易:
$user = User::attemptToCreate('email@example.com');
if(!$user) { // or if(is_null($user)) in case you return null instead of false
echo "Not logged.";
} else {
echo $user->name; // e.g.
}
您可以在此處進行測試:[http://ideone.com/TDqSyi]
我發(fā)現(xiàn)我的解決方案比拋出和捕獲異常更方便使用。
Al.G. answered 2020-06-29T19:54:08Z
總結
以上是生活随笔為你收集整理的php构造函数里抛出异常_php-在类的构造函数中返回值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 昆仑胎菊的功效与作用、禁忌和食用方法
- 下一篇: 包一个牙齿要多少钱