簡體   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