2016-05-23 164 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