2016-05-23 161 views
0

假設setEmail1()方法設置電子郵件地址或者在電子郵件地址似乎錯誤時生成錯誤消息,那麼有沒有更優雅的方法,也許只有1行,以執行以下操作? :更優雅的PHP代碼

$email2 = $newCustomer->setEmail1($_SESSION['customer_new']['email2']); 
    if ($email2 !== true) $_SESSION['customer_new']['error']['email2'] = $email2; 

謝謝!

+2

單行=>三元運算=> http://php.net/manual/en/ language.operators.comparison.php –

+0

[PHP三元運算符澄清]的可能重複(http://stackoverflow.com/questions/3580461/php-ternary-operator-澄清) – rsz

回答

0

您可以執行以下操作。但是,爲什麼你想把所有文字都寫在一行呢?

$_SESSION['customer_new']['error']['email2'] = ($newCustomer->setEmail1($_SESSION['customer_new']['email2']) !== true) ? $email2 : null; 
+0

這對我不起作用:-(,since在我的情況會話變量應該包含由類方法生成的錯誤消息或者不應該被設置(沒有設置爲空)。 – mlattari

0
$_SESSION['customer_new']['error']['email2'] = $newCustomer->setEmail1($_SESSION['customer_new']['email2']) ?: null; 

?:運算符是三元運算符的一個變種:)

$x = $y ?: 0; 
// is equivalent to 
$x = $y ? $y : 0; 
+0

這對我不起作用,因爲在我的情況下,會話變量應該包含由類方法生成的錯誤消息,或者不應該被設置爲根本(未設置爲空)。 – mlattari

+0

如果你不想設置它,那麼沒有其他方法比你原來的文章。但是,如果對空值使用isset(),則會得到與未定義相同的結果。 isset()也比array_key_exists()更快 – Kulvar

0

有載列如下的例子,但爲了清晰和可讀性,他們通常不建議。它的要求當然是這些答案,但我會認真考慮這樣做。如果你必須調試這些代碼,那麼這些內存區域可能會很痛苦。我個人會看到類似這樣的東西,它的基本類沒有涉及的模式,但您可能希望查看類模式(如MVC或工廠模式)以使您的編碼更加標準化。

class.email.php

class email { 

    public function validateEmail($email_address) { 

     // add your validation here. format it in a readable 
     // manner and debugging/future updates will be a breeze. 

    return $result; 

    } 

} 

file.php

require_once('class.email.php'); 

// With a framework like MVC this would have been preloaded in 
// the controller, but we initialise it here. 
$class_obj = NEW email(); 

// and here is the one liner that you would see in your main file. 
$email = $class_obj->validateEmail($email); 
+0

我的類已經驗證了電子郵件,如果地址錯誤,方法setEmail1()返回存儲在$ _SESSION ['customer_new'] ['error'] ['email2 '] ;-) – mlattari

+0

然後你已經將邏輯與功能分開了。當他們讓代碼變得不易管理時,我不認爲有任何需求。 – Chris