繁体   English   中英

更优雅的PHP代码

[英]More elegant PHP code

假设方法setEmail1()设置电子邮件地址或如果电子邮件地址似乎有误,则生成错误消息,是否有一种更优雅的方法(也许仅用1行)来执行以下操作?

    $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;
$_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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM