假設setEmail1()方法設置電子郵件地址或者在電子郵件地址似乎錯誤時生成錯誤消息,那麼有沒有更優雅的方法,也許只有1行,以執行以下操作? :更優雅的PHP代碼
$email2 = $newCustomer->setEmail1($_SESSION['customer_new']['email2']);
if ($email2 !== true) $_SESSION['customer_new']['error']['email2'] = $email2;
謝謝!
假設setEmail1()方法設置電子郵件地址或者在電子郵件地址似乎錯誤時生成錯誤消息,那麼有沒有更優雅的方法,也許只有1行,以執行以下操作? :更優雅的PHP代碼
$email2 = $newCustomer->setEmail1($_SESSION['customer_new']['email2']);
if ($email2 !== true) $_SESSION['customer_new']['error']['email2'] = $email2;
謝謝!
您可以執行以下操作。但是,爲什麼你想把所有文字都寫在一行呢?
$_SESSION['customer_new']['error']['email2'] = ($newCustomer->setEmail1($_SESSION['customer_new']['email2']) !== true) ? $email2 : null;
這對我不起作用:-(,since在我的情況會話變量應該包含由類方法生成的錯誤消息或者不應該被設置(沒有設置爲空)。 – mlattari
$_SESSION['customer_new']['error']['email2'] = $newCustomer->setEmail1($_SESSION['customer_new']['email2']) ?: null;
?:運算符是三元運算符的一個變種:)
$x = $y ?: 0;
// is equivalent to
$x = $y ? $y : 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);
單行=>三元運算=> http://php.net/manual/en/ language.operators.comparison.php –
[PHP三元運算符澄清]的可能重複(http://stackoverflow.com/questions/3580461/php-ternary-operator-澄清) – rsz