假设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