假设方法setEmail1()设置电子邮件地址或生成错误消息,如果电子邮件地址似乎是错误的,是否有更优雅的方式,可能只有1行,以执行以下操作? :
$email2 = $newCustomer->setEmail1($_SESSION['customer_new']['email2']);
if ($email2 !== true) $_SESSION['customer_new']['error']['email2'] = $email2;
谢谢!
答案 0 :(得分:0)
您可以执行以下操作。但是你为什么要写一行呢?
$_SESSION['customer_new']['error']['email2'] = ($newCustomer->setEmail1($_SESSION['customer_new']['email2']) !== true) ? $email2 : null;
答案 1 :(得分:0)
$_SESSION['customer_new']['error']['email2'] = $newCustomer->setEmail1($_SESSION['customer_new']['email2']) ?: null;
?:运算符是三元运算符的变体:)
$x = $y ?: 0;
// is equivalent to
$x = $y ? $y : 0;
答案 2 :(得分: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);