简体   繁体   English

更优雅的PHP代码

[英]More elegant PHP code

Assuming that the method setEmail1() sets the email address or generates error messages if the email address seems to be wrong, is there a more elegant way, maybe in only 1 line, to do the following ? 假设方法setEmail1()设置电子邮件地址或如果电子邮件地址似乎有误,则生成错误消息,是否有一种更优雅的方法(也许仅用1行)来执行以下操作? :

    $email2 = $newCustomer->setEmail1($_SESSION['customer_new']['email2']); 
    if ($email2 !== true) $_SESSION['customer_new']['error']['email2'] = $email2;

Thank You ! 谢谢 !

You could do the following. 您可以执行以下操作。 But why do you wanna write all in one line? 但是,为什么要全部写成一行?

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

The ?: operator is a variant of the ternary operator :) ?:运算符是三元运算符的变体:)

$x = $y ?: 0;
// is equivalent to
$x = $y ? $y : 0;

There are examples set out below, but for clarity and readability they are not usually advised. 下面列出了一些示例,但为清楚起见,通常不建议这样做。 Its what you asked for of course so those are the answers but I would seriously reconsider doing that. 当然是您要的,所以这些就是答案,但是我会认真考虑这样做。 If you have to debug the code those one liners can be a pain the nether regions. 如果您必须调试代码,那么那片衬里可能是一个让人痛苦的地方。

Personally I would be looking at something like this, its basic classes no pattern involved but you may want to look into class pattern such as MVC or the factory pattern to make your coding more standardised. 我个人将看这样的东西,它的基本类不涉及任何模式,但是您可能希望研究诸如MVC或工厂模式之类的类,以使您的编码更加标准化。

class.email.php 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 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