日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

php构造函数里抛出异常_php-在类的构造函数中返回值

發布時間:2024/9/18 php 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php构造函数里抛出异常_php-在类的构造函数中返回值 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

php-在類的構造函數中返回值

到目前為止,我有一個帶有構造函數的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的功能是在數據庫中查找特定的電子郵件地址。當我將標識符設置為某些電子郵件時,我確定它不在數據庫中; 第一個IF被傳遞,并轉到第一個ELSE。 這里的構造函數應該返回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

構造函數不會獲得返回值。 它們完全用于實例化該類。

在不調整您已經在做的事情的情況下,您可以考慮在此處使用異常。

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);

}

}

現在,您可以以這種方式創建新用戶。

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

構造函數假設要創建一個對象。 由于在php中,布爾值不被視為對象,因此唯一的選擇是null。 否則,請使用變通辦法,即編寫創建實際對象的靜態方法。

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

您能做的最好的就是史蒂夫的建議。除了將構造函數參數分配給對象屬性之外,不要創建執行任何工作的構造函數,不要創建一些默認參數,而別無其他。構造函數旨在創建功能齊全的對象。此類對象在實例化后必須始終按預期工作。用戶具有電子郵件,姓名以及其他一些屬性。當您要實例化用戶對象時,請將所有這些屬性提供給其構造函數。拋出異常也不是一個好方法。在異常情況下應拋出異常。通過電子郵件詢問用戶并不是什么例外,即使您最終發現不存在這樣的用戶。例如,如果您通過email =”來請求用戶,則可能是例外(除非這是系統中的常規狀態,但id則建議電子郵件在這些情況下為空)。要獲得用戶對象的所有這些屬性,您應該有一個工廠(或存儲庫,如果您愿意的話)對象(是的,一個對象-無論如何使用靜態方法都是不好的做法)私有構造函數也不是一個好習慣(無論如何,您都需要一個靜態方法,正如我已經說過的,靜態函數非常糟糕)

所以結果應該是這樣的:

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

}

看啊 沒有靜態,沒有異常,簡單的構造函數以及非常易讀,可測試和可修改的

slepic answered 2020-06-29T19:51:47Z

3 votes

構造函數只能返回嘗試創建的對象,而不能返回任何東西。 如果實例化無法正確完成,您將發現一個擁有try/catch個屬性的類實例。

如果對象加載時處于不完整或錯誤狀態,我建議設置一個屬性來表明這一點。

// 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";

}

}

然后,在實例化對象時,可以檢查它是否具有錯誤狀態:

$obj = new MyObject($identifier);

if (!empty($obj->error)) {

// something failed.

}

另一個(也許更好)的選擇是在構造函數中引發異常,并將實例化包裝在try/catch中。

Michael Berkowski answered 2020-06-29T19:52:21Z

2 votes

為什么不簡單地將結果傳遞給構建對象所需的構造函數,而不是嘗試使構造函數有時失敗?

即使有時使它失敗,您仍然需要在調用構造函數之后進行檢查以確保它確實進行了構造,并且在這些行中,您只需調用-> loadUser()并將結果傳遞給構造函數即可。

有人告訴我,這是一個很好的提示:“總是向構造函數提供構建對象所需的內容,而不是讓它去尋找它。”

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

我不會在結構中投入太多。 您應該考慮使用靜態函數來創建User(工廠),而不是將所有內容都放在構造函數中。 因此,您仍然可以使用用戶對象,而不必隱式調用load函數。 這樣可以減輕您的痛苦。

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的觀看者建議創建私有構造函數和試圖創建這樣的對象的方法:

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)。 捕獲這兩種情況現在非常容易:

$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]

我發現我的解決方案比拋出和捕獲異常更方便使用。

Al.G. answered 2020-06-29T19:54:08Z

總結

以上是生活随笔為你收集整理的php构造函数里抛出异常_php-在类的构造函数中返回值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。